程式碼一多,為了撰寫與維護的方便,最好的方法就是將一個.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)
{
    return 0;
}

把它切成多個 File... 包括 .h && .cpp
a.h的內容
----------
#ifndef A_H
#define A_H
void a_function();
void a_problem_function()
{
    int problem;
}
#endif

a.cpp的內容
----------
#include "a.h"
void a_function()
{
    int a;
}

main.cpp的內容
----------
#include<iostream>
#include "a.h"
int main(int argc, char**argv)
{
    return 0;
}
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檔裡,是很不明智的決定!!!
-------------------------------------------------------------------------------------
<Brief Conclusion>
a.c  =>   function, include "header", (definition, variable)
a.h  =>   function prototype, structure, (definition, variable)

arrow
arrow
    全站熱搜

    BB 發表在 痞客邦 留言(0) 人氣()