在 LearnCpp.com | 1.10 — A first look at the preprocessor .在 Header guards 下,有这些代码片段:
添加.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"
在实现header guard时,提到如下:
#ifndef ADD_H
#define ADD_H
// your declarations here
#endif
- 这里的声明可能是什么?而且,
int main()
应该在#endif
之后吗? - 添加
_H
是约定还是必须做的事情?
谢谢。
最佳答案
FILENAME_H
是一个约定。如果你真的想要,你可以使用 #ifndef FLUFFY_KITTENS
作为 header 保护(前提是它没有在其他任何地方定义),但如果你在其他地方定义它,那将是一个棘手的错误,比如数字小猫的东西或其他。
在头文件 add.h 中,声明实际上位于 #ifndef
和 #endif
之间。
#ifndef ADD_H
#define ADD_H
#include "mymath.h"
int add(int x, int y);
#endif
最后,int main()
不应该在头文件中。它应该始终位于 .cpp
文件中。
清除它:
#ifndef ADD_H
基本意思是“如果 ADD_H 没有在文件或包含文件中#defined
,则编译 #ifndef
和 #endif
指令”。因此,如果您尝试在 .cpp
文件中多次 #include "add.h"
,编译器将看到 ADD_H 已经是 #defined
并且将忽略 #ifndef
和 #endif
之间的代码。 header 保护仅防止 header 文件多次包含在同一个 .cpp
文件中。头文件保护不会阻止其他 .cpp
文件包含头文件。但所有 .cpp
文件都可以包含 protected 头文件仅一次。
关于c++ - C++ 和 C 中的 header 保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4767068/