Search code examples
cfunctioncall

What is the correct way to use static functions?


I have this code, which works, but I don't think I'm doing it the right way. I have 3 files, main.c, init.c and init.h.

init.h file looks like this (I omitted preprocessor directives in this example for simplicity):

void init(int param);

int firstCFG(int param);
int secondCFG(int param);
int thirdCFG(int param);
int fourthCFG(int param);
int fifthCFG(int param);

and the init.c file looks like this:

#include "init.h"

void init(int param){
   int cfg1 = firstCFG(1);
   int cfg2 = secondCFG(2);
   int cfg3 = thirdCFG(3);
   int cfg4 = fourtCFG(4);
   int cfg5 = fifthCFG(5);
}

int firstCFG(int param){
   //do stuff
   return stuff;
}
int secondCFG(int param){
   //do stuff
   return stuff;
}
int thirdCFG(int param){
   //do stuff
   return stuff;
}
int fourthCFG(int param){
   //do stuff
   return stuff;
}
int fifthCFG(int param){
   //do stuff
   return stuff;
}

and from my main.c file I call it like this:

#include "init.h"

int main(int argc, char** argv) {

    init(0);

    //do stuff....
}

So basically, I call only one function in init.c - init(); and other functions within that file are called from that file itself. But since I included init.h in the main file, I can call all CFG functions from main but I don't want to be able to. I want main.c file to see only the init() function and CFG functions to be private for the init.c. So my question is, what is the right way to do this?

My initial though was to make the CFG functions static and don't do #include "init.h" in main.c so only init() is extern. That worked too but the the compiler gave me warning warning: implicit declaration of function ‘init’


Solution

  • I'd put only the void init(int param); prototype in init.h. Make all the CFG functions static in init.c.

    You will still need prototypes for the CFG functions (unless you move init() to the end), but you could just declare them in init.c. Or you could put them in a separate init_impl.h file that is not available for users of your module to #include.