2011-01-22 54 views
0

在:http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/C++ - 我怎樣才能避免這個標題出現兩次?

在部首警衛,還有那些代碼片斷:

add.h:

#include "mymath.h" 
int add(int x, int y); 

subtract.h:

#include "mymath.h" 
int subtract(int x, int y); 

main.cpp中:

#include "add.h" 
#include "subtract.h" 

如何避免#include "mymath.h"main.cpp中出現兩次?

感謝。

+0

爲什麼你想避免它包括兩次? – sth 2011-01-22 17:24:54

回答

4

右低於實施例中的行解釋。你mymath.h文件應該是這樣的:

#ifndef MYMATH_H 
#define MYMATH_H 

// your declarations here 

#endif 

每頭文件應該遵循這個基本格式。這允許任何需要它的文件(頭文件和源文件)都包含頭文件,但實際的聲明在每個源文件中最多隻能包含一次

1

你應該把你的頭文件放在任何頭文件中,也可以放在mymath.h文件中。

4

使用#pragma一旦如果使用MS VC++或標準方式

內部mymath.h

#ifndef MYMATH_H 
#define MYMATH_H 

[code here] 

#endif // MYMATH_H 
2

這沒關係,如果他們包括兩次,如果全部頭文件有標頭警衛。第二個和所有後續的包含只會添加空行,並且不會有任何代碼重複。只要確保mymath.h也有標頭警衛。