[問題] 關於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