Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why before ALL functions (except for main()) there is a 'static' keyword?

Tags:

c

static

I was reading some source code files in C and C++ (mainly C)... I know the meaning of 'static' keyword is that static functions are functions that are only visible to other functions in the same file. In another context I read up it's nice to use static functions in cases where we don't want them to be used outside from the file they are written...

I was reading one source code file as I mentioned before, and I saw that ALL the functions (except the main) were static...Because there are not other additional files linked with the main source code .c file (not even headers), logically why should I put static before all functions? From WHAT should they be protected when there's only 1 source file?!

EDIT: IMHO I think those keywords are put just to make the code look bigger and heavier..

like image 553
ggg Avatar asked Nov 27 '22 15:11

ggg


2 Answers

If a function is extern (default), the compiler must ensure that it is always callable through its externally visible symbol.

If a function is static, then that gives the compiler more flexibility. For example, the optimizer may decide to inline a function; with static, the compiler does not need to generate an additional out-of-line copy. Also, the symbol table will smaller, possibly speeding up the linking process too.

Also, it's just a good habit to get into.

like image 130
ephemient Avatar answered Dec 18 '22 08:12

ephemient


It is hard to guess in isolation, but my assumption would be that it was written by someone who assumes that more files might be added at some point (or this file included in another project), so gives the least necessary access for the code to function. Essentially limiting the public API to the minimum.

like image 45
Marc Gravell Avatar answered Dec 18 '22 09:12

Marc Gravell