Home > Enterprise >  Static functions can't be called from any other file vs static function created in header file
Static functions can't be called from any other file vs static function created in header file

Time:02-03

Can anyone tell me how a static function created in header file can be invoked in other files, though static function which is not created in header file can't be invoked in other files. What exactly happens when we declare static functions in header file vs other cpp/c files.

CodePudding user response:

The "file" is a more or less meaningless concept in C and C - what matters is the "translation unit".

Somewhat simplified, when you compile one source file, that's one translation unit.
The #include mechanism is extremely simple - it literally just includes the contents of a file at that point.
And static makes a name local to the translation unit; it can't be seen anywhere else.

So, say you have a header "H.h":

static something X;

and two source files,

A.cpp:

#include "H.h"

and B.cpp:

#include "H.h"

then after preprocessing, this is what the compiler sees:

A.cpp:

static something X;

and B.cpp:

static something X;

In other words, you have two somethings called "X", completely independent of each other, and neither translation unit can access the other's.

(This is a frequent source of bugs that can be very hard to find, in particular if the intent is to have a globally mutable variable. Don't make things static in headers.)

CodePudding user response:

If you define static function in a header file it will be be visible in any source file which includes this header file. You will have as many copies of the static function as you have source files that include it. It will increase the program size. I would suggest only defining static inline functions in the header files.

It is a common misunderstanding in C. Beginner programmers think that the header file is a "library" but in the fact "#include" only textually replaces #include <file.h> with the context of file.h creating one source file which is compiled by the compiler.

Example: https://godbolt.org/z/Y5s9fecP6

  • Related