1. 程式人生 > >multiple definition of 問題解決方法

multiple definition of 問題解決方法

問題描述:有一個opt_process.h檔案,兩個.cc檔案都引用了這個.h檔案,在.h檔案中聲明瞭一些全域性變數,報錯
/tmp/ccBCSKoH.o:(.bss+0x0): multiple definition of longopts'
/tmp/ccZP3F8G.o:(.bss+0x0): first defined here
/tmp/ccBCSKoH.o:(.bss+0xc0): multiple definition of
input_opts’
/tmp/ccZP3F8G.o:(.bss+0xc0): first defined here
/tmp/ccBCSKoH.o:(.bss+0x100): multiple definition of inout_opts'
/tmp/ccZP3F8G.o:(.bss+0x100): first defined here
/tmp/ccBCSKoH.o:(.bss+0x140): multiple definition of

output_opts’
/tmp/ccZP3F8G.o:(.bss+0x140): first defined here
collect2: error: ld returned 1 exit status
原因:好像是由於多次包含,然後編譯.cc檔案是重複 定義了。
解決方法

  1. 使用extern關鍵字,即變數在.c檔案中宣告,在.h中用extern標誌即可;
  2. 用#ifndef+#define+#endif
  3. 如果全域性變數是常量,使用const標誌該常量(C++中),因為const常量在便宜期已經確定,無需編譯,自然也沒有重複定義的問題了。

1,2方法網上都有, 3方法自己實測有用,不足之處多多指教。