Search code examples
cinterfaceheaderfunction-prototypesc-header

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


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;
}

Solution

  • 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.