How to make a function visible through a header file in C

1.5k views Asked by At

I have several header files in a library: header1.h, header2.h... I also have a general header file for the library: mylib.h

I want the user to import the main.h file and get access to only some of the functions in the other header files.

For example, in the library:

// header1.h
void a(void);
void b(void);

-

// mylib.h

// I can't use this:
#include "header1.h"
// because it would make b function visible.

// Link to function a ????????

And in my main program:

// main.c
#include "mylib.h"

int main(void) {

    a(); // Visible: no problem
    b(); // Not visible: error

    return 0;
}
3

There are 3 answers

2
alk On BEST ANSWER

Separate function prototypes into different headers, depending on whether they should be "visible"*1 or not (but be "internal").

  • header1_internal.h
  • header1.h
  • header2_internal.h
  • header2.h
  • ...

Include into the *_internal.h headers the related *.h header.

Include the *_internal.h headers into your lib's related modules.

Do not include any *_internal.h into mylib.h.


*1: Please note that even when not providing a prototype this way the user might very well craft his/her own prototype and then link the function from mylib. So the functions not prototyped aren't unaccessible.

1
Smit Patel On

Header files only contains functions that should be accessible by user of header. They represent public interface.

Watch this first: Organizing code into multiple files 1 YouTube link: Organizing code into multiple files 1

Organizing code into multiple files 2 youTube link: Organizing code into multiple files 2

Additionally you can refer Introduction To GCC by Brian Gough to get more insights into compilation and linking process using gcc.

0
raymai97 On

If void b(void) is not needed by other header file, and you have access to the source file, what about moving the declaration into the source file?

// header1.h
void a(void);
//void b(void);

// header1.c
/* some #include here */
void b(void);
/* other code here */
void b(void) {
    /* implement it */
}