如何让编译器捕获两个C源文件中全局变量类型不一致的问题
my1.c
extern float e;
void f1(){ e=3.0;}
my2.c
#include <stdio.h>
int e=0;
void f1();
void main(){
printf("%d in main \n", e);
f1();
printf("%d in main \n", e);
}
这里全局变量e
在两个源文件中被错误地声明为float
和int
。
如何让链接器因这种不一致而引发错误?
my1.c
extern float e;
void f1(){ e=3.0;}
my2.c
#include <stdio.h>
int e=0;
void f1();
void main(){
printf("%d in main \n", e);
f1();
printf("%d in main \n", e);
}
Here the global variable e
is mistakenly declared as float
and int
in two source files.
How to let the linker raise error for this inconsistency?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们使用头文件而不是链接器来减轻这种风险。多个翻译单元中引用的任何内容都应在一个头文件中声明:
MyGlobal.h:
任何使用它的文件都应包含头文件:
main.c:
只有一个文件应定义它,并包含头文件:
MyGlobal.c :
通过使用头文件,所有翻译单元中的声明都是相同的。由于定义标识符的源文件还包括头文件,因此编译器会报告任何不一致。
头文件之外的任何外部声明(不是定义)都是可疑的,应该避免。
We mitigate this risk using header files, not the linker. Anything referred to in multiple translation units should be declared in one header file:
MyGlobal.h:
Any file that uses it should include the header file:
main.c:
Exactly one file should define it, and include the header file:
MyGlobal.c:
By using a header file, the declaration is identical in all translation units. Because the source file that defines the identifier also includes the header file, the compiler reports any inconsistency.
Any external declarations (that are not definitions) outside of header files are suspect and should be avoided.
1.c
2.c
1.c
2.c