程式碼一多,為了撰寫與維護的方便,最好的方法就是將一個.cpp檔切割成多個檔案(.cpp & .h )
但是最近撰寫了一支程式,把它切成多個file,卻莫名其妙地出現了"multiple definition of [function name] ... "這種錯誤訊息...
我仔細地觀察了又觀察,不管是正著看、反著看、倒著看…都看不出錯誤來…正當對分檔的寫法失望之餘,想回復到原本一個檔案的寫法後,才驚覺原本寫法的漏洞與缺點…
原本的一個file寫到底的code....
#include<iostream>void a_function(){int a;}void a_problem_function(){int problem;}int main(int argc,char**argv){return0;}把它切成多個file... 包括 .h && .cpp
a.h的內容
#ifndef A_H #define A_H void a_function();void a_problem_function(){int problem;}#endifa.cpp的內容
#include"a.h"void a_function(){int a;}main.cpp的內容
#include<iostream>#include"a.h"int main(int argc,char**argv){return0;}compile過程:
% g++ -c a.cpp % g++ a.o main.cpp ...... multiple definition of `a_problem_function()'
照上面的寫法實作後 會產生這樣的問題...
奇怪!? 明明a.h不是寫了「#ifndef ... #define .... 」怎麼還會有問題呢!?
沒錯! 這樣的寫法的確是會有問題的... 並不是說寫了「#ifndef ... #define .... 」,在compile過程中,就應該只有一份a_problem_function() 而不應該出現multiple definition的問題才對呀...
其實問題是在於g++ -c a.cpp後,產生了a.o檔,這個a.o檔裡面,已經包含了一個a_problem_function()的definition,然而接下來g++ a.o main.cpp時,main.cpp又去include a.h,因此,它又想產生了一份a_problem_function(),問題就此產生了!
所以把變數definition寫入.h檔也會產生一樣的問題喲!
所以問題的徵結就在於.h檔裡面,寫入了function的definition或是變數definition,這樣子容易在多個檔案互相include時,產生multiple definition的問題,所以說囉,千萬別偷懶…直接把function definition寫在.h檔裡,是很不明智的決定!!!
文章標籤
全站熱搜
