【发布时间】:2015-06-19 01:17:57
【问题描述】:
我读到了
具有内部链接的函数仅对一个编译可见 单元。 (...) 声明为静态的函数具有内部链接
对于.c 文件,它有点意思,但我想知道标题中的静态函数会发生什么情况,它们被多个.c 文件包含但通常有一个包含保护。
我正在阅读this answer 关于标题中的静态函数的信息,第一项提到它不会创建具有外部链接的符号,第二项提到该函数完全可以通过头文件获得。这不矛盾吗?该功能如何可用,同时又没有外部符号?所以我做了一个小测试:
/* 1.h */
#ifndef ONE_H
#define ONE_H
#include <stdio.h>
static void foo() {
printf("foo from 1.h %p\n", foo);
return;
}
void bar();
#endif
/* 1.c */
#include "1.h"
#include <stdio.h>
void bar() {
printf("foo,bar from 1.c %p,%p\n", foo, bar);
foo();
}
/* 2.c */
#include "1.h"
#include <stdio.h>
int main() {
printf("foo,bar from main %p,%p\n", foo, bar);
foo();
bar();
return 0;
}
...
debian@pc:~ gcc 2.c 1.c
debian@pc:~ ./a.out
foo,bar from main 0x400506,0x400574
foo from 1.h 0x400506
foo,bar from 1.c 0x400559,0x400574
foo from 1.h 0x400559
正如预期的那样,bar 在所有文件中都是相同的,但foo 不应该也是如此吗? 1.h 不是只包含一次吗?将inline 添加到foo 会导致相同的行为。我有点迷路了。
【问题讨论】:
-
1.h 在任何特定的翻译单元中都包含一次。 IE。在任何一个 .C 文件中。您的代码有 2 个 .c 文件,每个 .c 文件中都包含一个