[问题] 关于multiple definition

楼主: james732 (好人超)   2019-06-26 12:39:58
开发平台(Platform): (Ex: Win10, Linux, ...)
Linux
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
问题(Question):
test.h
#ifndef TEST_H_
#define TEST_H_
int test; /* 把变量定义写在.h */
void foo();
#endif
test1.c
#include "test.h"
void foo()
{
test = 5;
}
test2.c
#include "test.h"
int main()
{
foo();
printf("test = %d\n", test);
}
以上的程式码,如果使用gcc test1.c test2.c去编译
不会有任何错误或警告,会顺利的把执行档build出来
看起来执行结果好像也是对的
但如果是用g++ test1.c test2.c去编译就会错误:
/tmp/ccQ45lbS.o:(.bss+0x0): multiple definition of `test'
/tmp/ccEQnw6g.o:(.bss+0x0): first defined here
想请问的是:C语言用这样的写法是安全的吗?
如不考虑C++的相容性,有没有什么情况下会发生出乎意料的执行结果?
(换句话说,这样的写法会不会有隐藏什么地雷?)
作者: Bencrie   2019-06-26 12:55:00
每个 include test.h 的 obj 都有一份 test 没错啊
作者: a27417332 (等号卡比)   2019-06-26 12:58:00
应该是C的tentative definition吧
作者: KaryuuIssen (一闪)   2019-06-26 12:59:00
C允许多重宣告全域变量
作者: a27417332 (等号卡比)   2019-06-26 13:01:00
C++也可以多个“宣告”呀
作者: tinlans ( )   2019-06-26 13:19:00
就是 C 才有的 tentative definition,在 C++ 不存在C 这样写是安全的,只有未初始化的全域变量定义才能用这条规则,底层的原理是使用 common symbols。
作者: chuegou (chuegou)   2019-06-26 13:58:00
推个

Links booklink

Contact Us: admin [ a t ] ucptt.com