[問題] 關於multiple definition
開發平台(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
06/26 12:55, 1F
→
06/26 12:58,
4年前
, 2F
06/26 12:58, 2F
推
06/26 12:59,
4年前
, 3F
06/26 12:59, 3F
→
06/26 13:01,
4年前
, 4F
06/26 13:01, 4F
→
06/26 13:19,
4年前
, 5F
06/26 13:19, 5F
→
06/26 13:27,
4年前
, 6F
06/26 13:27, 6F
→
06/26 13:28,
4年前
, 7F
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