Why C ++ header files you want to add #ifndef #define #endif

#Ifndef role in the header file

In a large software engineering inside, there may be more than one file contains a header file, when these files are compiled and linked into an executable file

, Will be a large mistake "redefinition" appears. In the header file utility to avoid #ifndef #define #endif redefinition header file.

Methods: For example, to write the header file test.h

At the beginning of the header file written on two lines:

#ifndef _TEST_H

#define _TEST_H // usually capitalized filenames

The end of the header file written on one line:

#endif

When such a project file contains two test.h, will not be re-defined error occurred.

Analysis: When test.h comprising first, since there is no definition of _TEST_H, the condition is true, this will comprise (execution) #ifndef _TEST_H and

Code between #endif, when the second time has been defined comprises a front test.h _TEST_H, the condition is false, # ifndef _TEST_H and

Code between #endif will not be included again, thus avoiding redefined.

 

#include "test.h"

#include "debug.h"

 

If the code is as follows debug.h

#include "a.h"

#include "test.h"

This includes the repeated "test.h"

 

If #ifndef #define #endif statement is possible to prevent repeated comprise test.h defined,

When test.h comprising first, since there is no definition of _TEST_H, the condition is true, this will comprise (execution) #ifndef _TEST_H and

Code between #endif, when the second time has been defined comprises a front test.h _TEST_H, the condition is false, # ifndef _TEST_H and

Code between #endif will not be included again, thus avoiding redefined.

The main header file to prevent the repeat of the global variable is defined, it is recommended not to define variables in the header file.

 

problem:

#include "test.h" compiler which actions? ?

You can see through the debugging process #include and effect?

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

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

 

"Header files are repeatedly cited" What does it mean?

A: Actually , "repeated references" refers to a header file in the same cpp file was include several times, often because of this error include nested caused.

For example: there is ah file #include "ch", while at the same time b.cpp file #include "ah" and #include "ch", at this time will cause ch is b.cpp duplicate references.

I feel this sentence there is a problem? ?

I understand, uncertain right:

 

If you use macros written:

// B.cpp 
#include " AH " // execution, include ch, leading to the definition of C_H 
#include " CH " // execution, include ch, because the line has been defined C_H, so the condition is false, # define what code not implemented
// a.h
#ifndef A_H
#define A_H

#include "c.h"

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

//pass

#endif

 

 

Guess you like

Origin www.cnblogs.com/focus-z/p/11415468.html