用C ++标题保护 [英] Header guards in C++

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

问题描述

LearnCpp.com | 1.10 - 首先看预处理器。在标头警卫下,有这些代码片段:

add.h:

  #includemymath.h
int add(int x,int y);

subtract.h:

  #includemymath.h
int subtract(int x,int y);

main.cpp:

  #includeadd.h
#includesubtract.h

在实现头文件后台中,提到如下:

  #ifndef ADD_H 
#define ADD_H

//您在这里的声明

#endif




  • 声明可以在这里?并且,应该 int main()出现在 #endif 之后

  • 添加 _H 约定或必须做的事情



p>

解决方案

FILENAME_H 是一个惯例。如果你真的想要的话,你可以使用 #ifndef FLUFFY_KITTENS 作为头部守卫(假设它没有在其他地方定义),但是如果你在某处定义了它,那将是一个棘手的错误else

在头文件add.h中,声明在字面上介于 #ifndef

之间, code>和 #endif

  #ifndef ADD_H 
#define ADD_H

#includemymath.h
int add(int x,int y);
$ b#b #endif

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



清除它:



#ifndef ADD_H 基本上意思是如果文件中的ADD_H不是 #defined 或者在一个包含的文件中,然后编译 #ifndef #endif 指令之间的代码。因此,如果您在 .cpp 文件中多次尝试 #includeadd.h,编译器将会看看ADD_H已经是 #defined ,并且会忽略 #ifndef #之间的代码ENDIF 。标题保护只能防止在同一个 .cpp 文件中多次包含头文件。标题保护不会阻止其他 .cpp 文件包含头文件。但是所有的 .cpp 文件都只能包含被保护的头文件


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:

#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

  • What could the declaration be here? And, should int main() come after #endif?
  • Is adding _H a convention or a must do thing?

Thanks.

解决方案

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.

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

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

To clear it up:

#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 ++标题保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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