wef*_*fa3 2 c linker static symbols external
我发现一些与extern和static(内部)变量有关的行为,我觉得很奇怪。
这是一个例子:
/* file a.c */
#include <stdio.h>
/* variable with static linkage */
static int x = 24;
int f() {
/* variable with extern linkage */
extern int x;
return x;
}
int main() {
printf("%d\n", f());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
--
/* file x.c */
/* define symbol `x` to be an `int` equal to 100 */
int x = 100;
Run Code Online (Sandbox Code Playgroud)
我使用以下命令编译该程序:
$ cc a.c x.c -o a
Run Code Online (Sandbox Code Playgroud)
然后,我运行程序并获得以下输出:
$ ./a
24
Run Code Online (Sandbox Code Playgroud)
为什么该程序输出24而不是100?