[問題] 關於multiple definition

看板C_and_CPP作者 (好人超)時間4年前 (2019/06/26 12:40), 4年前編輯推噓3(305)
留言8則, 5人參與, 4年前最新討論串1/1
開發平台(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++的相容性,有沒有什麼情況下會發生出乎意料的執行結果? (換句話說,這樣的寫法會不會有隱藏什麼地雷?) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.71.214.246 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1561524000.A.C14.html

06/26 12:55, 4年前 , 1F
每個 include test.h 的 obj 都有一份 test 沒錯啊
06/26 12:55, 1F

06/26 12:58, 4年前 , 2F
應該是C的tentative definition吧
06/26 12:58, 2F

06/26 12:59, 4年前 , 3F
C允許多重宣告全域變數
06/26 12:59, 3F

06/26 13:01, 4年前 , 4F
C++也可以多個「宣告」呀
06/26 13:01, 4F

06/26 13:19, 4年前 , 5F
就是 C 才有的 tentative definition,在 C++ 不存在
06/26 13:19, 5F

06/26 13:27, 4年前 , 6F
C 這樣寫是安全的,只有未初始化的全域變數定義才能用這
06/26 13:27, 6F

06/26 13:28, 4年前 , 7F
條規則,底層的原理是使用 common symbols。
06/26 13:28, 7F

06/26 13:58, 4年前 , 8F
推個
06/26 13:58, 8F
非常感謝大家的迅速回覆,這樣我就放心了 :) ※ 編輯: james732 (111.71.214.246 臺灣), 06/26/2019 14:05:04
文章代碼(AID): #1T4lSWmK (C_and_CPP)