2011-09-25 93 views
0

說我有一個非常小的頭文件,像這樣:問題「多重定義」

#ifndef A_H_ 
#define A_H_ 

void print(); 
int getInt() 
{ //ERROR HERE 
    return 5; 
} 

#endif /* A_H_ */ 

和源文件執行打印,像這樣:

#include "a.h" 

void print() 
{ 
    printf("%d\n",getInt()); //WARNING HERE 
} 

我的main()函數的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include "a.h" 

int main(void) 
{ 
    print(); 
    return EXIT_SUCCESS; 
} 

注意getInt在頭文件中定義,在源文件中調用。 我編譯時得到multiple definition of getInt'`在頭文件,但我只 定義一次吧!源文件(.c)僅調用它。我的問題是什麼? 感謝

+2

給出,這將彙編就好了。您真正的問題可能包括標題兩次,或將其包含在多個文件中。在一個問題張貼代碼 –

+0

規則一:請確保它實際上*重現問題*。你會自己找到解決方案。 –

回答

1

你可能包括你的頭文件到另一個源文件了。你可以嘗試將定義移動到.c文件或聲明getInt()inline

+0

真的,我包括這兩種變交流和main.c中,但我還是不明白的問題....請注意,我已經添加main.c中 – yotamoo

+1

代碼的問題是,C預處理器是啞巴。而'#include'的確如其名稱所暗示的那樣:它將文件的內容包含到另一個文件中。所以,當你嘗試編譯你的程序時,鏈接器會發現'getInt'在'main.c'和'a.c'中都被定義了,因此就是錯誤。將它聲明爲「inline」可以解決問題,因爲內聯函數的作用就好像它們沒有定義一樣,它們只有一個聲明。多個聲明都可以,但是定義必須是唯一的。 – cyco130

0

你應該移動到getInt()交流,即

啊:

#ifndef A_H_ 
#define A_H_ 

void print(void); 
int getInt(void); 

#endif /* A_H_ */ 

交流:

#include <stdio.h> 
#include "a.h" 

void print(void) 
{ 
    printf("%d\n",getInt()); 
} 

int getInt(void) 
{ 
    return 5; 
} 

的main.c:

#include <stdio.h> 
#include <stdlib.h> 
#include "a.h" 

int main(void) 
{ 
    print(); 
    return EXIT_SUCCESS; 
} 

作爲一個經驗法則,接口(即原型對外部訪問的功能,再加上相關的typedef和常數等)屬於在.h文件,而omplementations(即實際功能的定義,再加上專用(靜態)功能和其他內部的東西)在.c文件屬於。