[英]In C++, how can I avoid #including a header file when I need to use an enumeration?
[英]C++ - How can I avoid this header from appearing twice?
網址 : http : //www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/
在標題保護下,有以下代碼段:
add.h:
#include "mymath.h"
int add(int x, int y);
減去.h:
#include "mymath.h"
int subtract(int x, int y);
main.cpp:
#include "add.h"
#include "subtract.h"
如何避免#include "mymath.h"
在main.cpp
出現兩次?
謝謝。
該示例正下方的行對此進行了解釋。 您的mymath.h
文件應如下所示:
#ifndef MYMATH_H
#define MYMATH_H
// your declarations here
#endif
每個頭文件都應遵循此基本格式。 這允許頭文件被任何需要它的文件(頭文件和源文件)包括在內,但是實際的聲明最多只能在每個源文件中包含一次 。
如果您使用MS VC ++或標准方式,請一次使用#pragma
在mymath.h中
#ifndef MYMATH_H
#define MYMATH_H
[code here]
#endif // MYMATH_H
如果所有頭文件都具有頭保護,那么它們包括兩次就可以了。 第二個及所有后續包含項只會添加空行,並且不會重復任何代碼。 只要確保mymath.h
也具有頭文件后衛即可。
您應該將標題保護程序放在任何標題中,也應放在mymath.h中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.