开发者

extern keyword with function names

I know that static keyword makes a C function/variable is file-scoped. And I've read that If I want to make a variable global scope (accessed by more than one file), I should do:

in the .c file:

int my_global_var;

// main()....

in the .h file:

extern int my_global_var;

So, any one will include my .h file will be able to reference my_global_var which is already externed.

And I read also this is required for functions as well but I am using gcc 4.x and I don't extern t开发者_Python百科he function in the .h file and other programs can successfully link it.

So, the question is...

Is the behavior of the non-static function linkage is the default or should I extern non-static functions to adhere to the standard??


From the standard, 6.2.2

5 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

Meaning, it's extern by default.


Both function and object declarations are extern by default. However, you need to add an explicit extern to your object declarations in header files to avoid a re-definition: without a storage-class specifier, any file-scoped object declaration will actually be something called a tentative definition and reserve storage for the object within the current translation-unit.

For consistency, I unnecessarily use extern even for function declarations. In most cases, I declare objects within headers as one of

extern int foo;
static const int bar = 42;

and functions as one of

extern int spam(void);
static inline int eggs(void) { return 42; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜