C++ 和 C 中的标头保护

2022-01-11 00:00:00 c macros c++ include-guards header-files

在 LearnCpp.com |1.10 ― 预处理器初探.在 Header guards 下,有这些代码片段:

At LearnCpp.com | 1.10 ― A first look at the preprocessor. Under Header guards, there are those code snippets:

添加.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 是约定还是必须做的事情?
    • What could the declaration be here? And, should int main() come after #endif?
    • Is adding _H a convention or a must do thing?
    • 谢谢.

      推荐答案

      FILENAME_H 是一个约定.如果你真的想要,你可以使用 #ifndef FLUFFY_KITTENS 作为标头保护(前提是它没有在其他任何地方定义),但如果你在其他地方定义它,那将是一个棘手的错误,比如数字小猫的东西或其他.

      The FILENAME_H is a convention. If you really wanted, you could use #ifndef FLUFFY_KITTENS as a header guard (provided it was not defined anywhere else), but that would be a tricky bug if you defined it somewhere else, say as the number of kittens for something or other.

      在头文件 add.h 中,声明实际上位于 #ifndef#endif 之间.

      In the header file add.h the declarations are literally between #ifndef and #endif.

      #ifndef ADD_H
      #define ADD_H
      
      #include "mymath.h"
      int add(int x, int y);
      
      #endif
      

      最后,int main() 不应该在头文件中.它应该始终位于 .cpp 文件中.

      Finally, int main() shouldn't be in a header file. It should always be in a .cpp file.

      清除它:

      #ifndef ADD_H 基本意思是如果 ADD_H 没有在文件或包含文件中#defined,则编译 #ifndef#endif 指令".因此,如果您尝试在 .cpp 文件中多次 #include "add.h",编译器将看到 ADD_H 已经是 #defined 并且将忽略 #ifndef#endif 之间的代码.标头保护仅防止标头文件多次包含在同一个 .cpp 文件中.头文件保护不会阻止其他 .cpp 文件包含头文件.但所有 .cpp 文件都可以包含受保护的头文件仅一次.

      #ifndef ADD_H basically means "if ADD_H has not been #defined in the file or in an included file, then compile the code between #ifndef and #endif directives". So if you try to #include "add.h" more than once in a .cpp file, the compiler will see what the ADD_H was already #defined and will ignore the code between #ifndef and #endif. Header guards only prevent a header file from being included multiple times in the same .cpp file. Header guards don't prevent other .cpp files from including the header file. But all .cpp files can include the guarded header file only once.

相关文章