C++头文件为什么要加#ifndef #define #endif

#ifndef 在头文件中的作用

在一个大的软件工程里面,可能会有多个文件同时包含一个头文件,当这些文件编译链接成一个可执行文件时

,就会出现大量“重定义”的错误。在头文件中实用#ifndef #define #endif能避免头文件的重定义。

方法:例如要编写头文件test.h

在头文件开头写上两行:

#ifndef _TEST_H

#define _TEST_H                 //一般是文件名的大写

头文件结尾写上一行:

#endif

这样一个工程文件里同时包含两个test.h时,就不会出现重定义的错误了。

分析:当第一次包含test.h时,由于没有定义_TEST_H,条件为真,这样就会包含(执行)#ifndef _TEST_H和

#endif之间的代码,当第二次包含test.h时前面一次已经定义了_TEST_H,条件为假,#ifndef _TEST_H和

#endif之间的代码也就不会再次被包含,这样就避免了重定义了。

#include "test.h"

#include "debug.h"

如果 debug.h 内代码如下

#include "a.h"

#include "test.h"

这样就重复包含了 “test.h”

如果 test.h 定义时 使用 #ifndef #define #endif 语句可以防止重复包含,

当第一次包含test.h时,由于没有定义_TEST_H,条件为真,这样就会包含(执行)#ifndef _TEST_H和

#endif之间的代码,当第二次包含test.h时前面一次已经定义了_TEST_H,条件为假,#ifndef _TEST_H和

#endif之间的代码也就不会再次被包含,这样就避免了重定义了。

主要防止头文件里的全局变量重复定义,建议不要在头文件里定义变量。

问题:

#include “test.h” 编译器执行了哪些操作??? 

能否通过调试看到#include的过程和效果呢?

#include "hello.h"

包含头文件,实际是一个复制 粘贴的过程,把头文件中的所有内容复制到当前文件中。

Logically, that copy/paste is exactly what happens. I'm afraid there isn't any more to it. You don't need the ;, though.

Your specific example is covered by the spec, section 6.10.2 Source file inclusion, paragraph 3:

A preprocessing directive of the form

# include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

https://www.cnblogs.com/xuepei/p/4027946.html

https://www.cnblogs.com/hello-Huashan/p/5545244.html

https://stackoverflow.com/questions/5735379/what-does-include-actually-do

“头文件被重复引用”是什么意思?

答:其实“被重复引用”是指一个头文件在同一个cpp文件中被include了多次,这种错误常常是由于include嵌套造成的。

比如:存在a.h文件#include "c.h",而b.cpp文件同时#include "a.h" 和#include "c.h",此时就会造成c.h被b.cpp重复引用。

感觉这句话有问题呢??

我的理解,不确定对不对:

如果使用宏定义写法:

// b.cpp
#include "a.h"  // 执行,包含c.h,导致定义C_H
#include "c.h"  // 执行,包含c.h,因为上一行已经定义了C_H,所以条件为假,#define一下的代码没有执行
// a.h
#ifndef A_H
#define A_H

#include "c.h"

#endif
// c.h
#ifndef C_H
#define C_H

//pass

#endif
原文地址:https://www.cnblogs.com/focus-z/p/11415468.html