開發平台(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++的相容性,有沒有什麼情況下會發生出乎意料的執行結果?
(換句話說,這樣的寫法會不會有隱藏什麼地雷?)