This code will compile and is well defined under current C standards:
static int foo(int);
extern int foo(int);
The standard specifies that in this situation (C11: 6.2.2 Linkages of identifiers (p4)):
For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. [...]
... which means that the int foo(int)
function is declared static int foo(int)
.
Swapping these declarations around like this:
extern int foo(int);
static int foo(int);
...gives me a compiler error using GNU GCC:
static declaration of 'foo' follows non-static declaration
My question is: What is the design rationale behind the second case being an error and not handled in a similar way as the first case? I suspect it has something to do with the fact that separate translation units are easier to manage and #include
? I feel as though without understanding this, I can open myself up to some mistakes in future C projects.
int foo(int)
function is declaredextern int foo(int)
' comment is wrong. The priorstatic
declaration means that the function isstatic
. If you only declare externally visible functions in a header (where the declarations belong) and only declare static functions inside a source file, you won't ever run into problems. Headers don't declare static functions (unless the header definesstatic inline
functions). You can only run into problems if you are sloppy in the way you write the code. The C compiler allows you to be sloppy, but you shouldn't be.extern
declarations of variables in source files; they belong only in header files.static inline
is just a more verbose and less portable way of sayingstatic
, because the semantics ofinline
are approximately nothing, whilestatic
has very significant semantics in the language, and therefore actually communicates very useful information to an optimizing compiler. Relevantly, with optimizations turned up high enough in compilers likegcc
andclang
,static
does approximately infinitely more to inline functions thaninline
.inline
has some effects and semantics, but as far as I know those only change stuff forextern
functions, and if the definition of the function occurs multiple times in the same translation unit - but that's what include guards in headers are for. Anyway, personally, I've yet to run into issues with headers which have include guards and definestatic
helper functions withoutinline
, but maybe I'm missing some edge case?