2012-11-08 48 views
3

我知道預處理器命令是頭文件的重要組成部分,可以防止多次定義變量和類。爲什麼我的C++包含多次定義變量?

我一直遇到問題,我的變量被定義多次 - 即使使用預處理器包裝。這裏是遇到編譯器錯誤的示例項目:

部首:

// TestInclude.h 
#ifndef TESTINCLUDE_H_ 
#define TESTINCLUDE_H_ 

int myInt; 

#endif /*TESTINCLUDE_H_*/ 

C++:

// TestInclude.cpp 
#include <iostream> 
#include "IncludeMe.h" 
#include "TestInclude.h" 

int main(int argc, char* args[]) 
{ 
    std::cin >> myInt; 

    IncludeMe thisClass; 

    std::cin >> myInt; 
} 

部首:

// IncludeMe.h 
#ifndef INCLUDEME_H_ 
#define INCLUDEME_H_ 

class IncludeMe 
{ 
private: 
    int privateInt; 
public: 
    IncludeMe(); 
}; 

#endif /*INCLUDEME_H_*/ 

C++:

// IncludeMe.cpp 
#include <iostream> 
#include "IncludeMe.h" 
#include "TestInclude.h" 

IncludeMe::IncludeMe() 
{ 
    std::cout << "myInt: " << myInt; 
} 

然後我編譯如下:

的Makefile:

all: 
g++ -g -o TestInclude TestInclude.cpp IncludeMe.cpp 

而且我得到以下錯誤:

/tmp/ccrcNqqO.o: In function `IncludeMe':
/home/quakkels/Projects/c++/TestInclude/IncludeMe.cpp:6: multiple definition of `myInt'
/tmp/ccgo6dVT.o:/home/quakkels/Projects/c++/TestInclude/TestInclude.cpp:7: first defined here
collect2: ld returned 1 exit status
make: *** [all] Error 1

爲什麼我收到的時候我使用預處理器此錯誤我的頭文件中的條件?

回答

9

包括警衛不防止多重定義。它們只能防止無限遞歸包含。 (當然,您可以在多個翻譯單元中包含相同的標題!)

您不應在標題中包含對象定義*;只有聲明

header.hpp:

extern int a; 

file.cpp:

#include "header.hpp" 

int a = 12; 

*)您可以類定義在頭文件中,以及inline函數和類成員函數。

+0

'extern'做什麼? – quakkels

+0

形式上,它告訴編譯器,下面的聲明不是一個定義。簡單來說,它告訴編譯器聲明變量的定義是在其他地方,鏈接器應該解決它。 – MSalters

2

您應該在頭文件中使用extern int myInt;,並且只在需要定義它的單個.cpp文件中寫入int myInt;

有些項目使用像「IN_FOO_CPP」這樣的預處理器宏來使其自動使用#ifdefs進行。