在 Header File 中定義所要注意的細節~File Scope

請先看看下面的程式:

test.h

#ifndef _TEST_H_
#define _TEST_H_

int AAA( void )
{
printf("Hello!!\n");
return 0;
}

int BBB( void ); // defined in test1.c
int CCC( void ); // defined in test2.c

#endif

test1.c

#include
#include "test.h"

int BBB( void )
{
AAA();
printf( "Hello~ test1!!\n" );
return 0;
}

test2.c

#include
#include "test.h"

int CCC( void )
{
BBB();
printf( "Hello~ test2!!\n" );
return 0;
}

int main()
{
CCC();
return 0;
}

使用下面的指令進行編譯
gcc -c test1.c
gcc test1.o test2.c

結果看到下面的錯誤信息:
/tmp/ccSQ7VRf.o: In function `AAA':
test2.c:(.text+0x0): multiple definition of `AAA'
test1.o:test1.c:(.text+0x0): first defined here
collect2: ld returned 1 exit status

很吸引我注意的是「multiple definition」這字眼,因為在整個程式裡面,其實明明就只定義一次。

問題出在哪裡呢?恩,File Scope

在編譯 test1.o 的時候,因為 test1.c 中引入了 test.h,所以 test1.c 的程式展開後會包含 AAA 的定義。而當 test2.c 再去引入 test.h 並連結 test1.o 時,當然會發生重複定義的問題。

要避免這問題的方法,就是在 AAA 的定義裡面加上 static,這個以限制該 Function 的 file scope 只在 test1.c 裡面,自然 test2.c 要再去宣告是可以的~

我比較喜歡另外一種解法,用另一個檔案重新定義 AAA(不要放在 test.h),這樣不就好了~

留言

這個網誌中的熱門文章

我弟家的新居感恩禮拜分享:善頌善禱

如何將Linux打造成OpenFlow Switch:Openvswitch

Openssl 範例程式:建立SSL連線