c++ - C++ 和 C 中的 header 保护

标签 c++ c macros header-files include-guards

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/

相关文章:

c - splinter 的多线宏

c++ - C++ 宏展开的一个问题

C++ - 如何将回调绑定(bind)到类方法而不是静态的?

c++ - 为什么返回值不同?

c - 如何在libnl中定义nl_sock?

c - 声明后初始化数组

c++ - 在 Ubuntu for Windows 上构建 QT5 项目

c++ - 虚拟模板函数的替代方案

c - nel -= nel/2 在功能上等同于 nel/= 2 吗?

c++ - 用于编译时强制 constexpr 函数评估的单个表达式助手可能吗?