开发者

Internal linkage with static keyword in C

I know static is an overloaded keyword in C. Here, I'm only interested in its use as a keyword to enforce internal linkage.

If you have a global variable declared in a .c file, what is the difference between using static and not using static? Either way, no other .c file has access to the variable, so the variable is basically "private" to the file, with or without the static keyword.

For example, if I have a file foo.c, and I declare a global variable:

int x = 5;

That variable x is only available to code inside foo.c (unless of course I declare it in some shared header file with the extern keyword). But if I don't declare it in a header file, what would be the difference if I were to type:

static int x = 5.

Either way, it seems x has internal linkage here. So 开发者_Go百科I'm confused as to the purpose of static in this regard.


If you have a global variable declared in a .c file, what is the difference between using static and not using static? Either way, no other .c file has access to the variable [...]

A different file could declare x:

extern int x;

That would allow code referencing x to compile, and the linker would then happily link those references to any x it finds.

static prevents this by preventing x from being visible outside of its translation unit.


There is only one "namespace", so to speak, in C. Without the "static" keyword you are not protected from another file using the name "x" (even if you do not make it visible in your own library's header).

Try to link together several C files containing a non-static variable x (interleaving read and write accesses from functions in each file), and compare with the situation where these variables are declared static.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜