C/C++: Static function in header file, what does it mean?

Jarod picture Jarod · Apr 23, 2009 · Viewed 84.4k times · Source

I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.

Answer

unwind picture unwind · Apr 23, 2009

Is the function defined in the header file? So that the actual code is given directly in the function, like this:

static int addTwo(int x)
{
  return x + 2;
}

Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea.

Remember that #include:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file.

UPDATE: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) intrinsic functions can be expressed like the above, and with an explicit inline keyword even:

static inline int addTwo(int *x)
{
  __add_two_superquickly(x);
}

Here, the __add_two_superquickly() function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro.

The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used.