C ++和C中的标题保护 [英] Header guards in C++ and C

查看:83
本文介绍了C ++和C中的标题保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LearnCpp.com | 1.10 —首先看一下预处理器.在标题卫士下,有以下代码段:

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

add.h:

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

subtract.h:

subtract.h:

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

main.cpp:

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

在实施标头防护时,其说明如下:

In implementing the header guard, it is mentioned as follows:

#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的基本含义是如果文件或包含的文件中未包含#defined ADD_H,则在#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.

      这篇关于C ++和C中的标题保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆