What is the use of ifndef/define/endif in the header file?

For example: to write the header file test.h

         Write two lines at the beginning of the header file:

          #ifndef _TEST_H

          #define _TEST_H//It is usually the uppercase of the file name

         ············

         ············

         Write the following line at the end of the header file:

          #endif

    Probably because I haven't learned it before, I don't understand it very well, why use these? I checked the Internet just now, and learned from some experts. I summed up a little, and I wrote it here. If there is any mistake, please point out the heroes.

    1. For example, you have two C files, both of which include the same header file. When compiling, these two C files have to be compiled together into one executable file, so the problem comes, a large number of declaration conflicts.

E.g:

Suppose there are 4 files in your project, namely a.cpp, bh, ch, dh. 
The head of a.cpp is: 
#include "bh " 
#include "ch " 
The heads of bh and ch are: 
#include "dh " 
And dh has the definition of class D in it. 
In this way, 
when the compiler compiles a.cpp, it first compiles the bh problem according to #include "bh ", and then compiles the dh file according to the #include "dh" in bh. class D is compiled; 
then according to the second sentence of a.cpp #include "ch ", to compile ch, the class D in dh will eventually be found, but class D has been compiled before, so it will be reported again. Definition error. Add ifndef/define/endif to prevent this redefinition error.

So put the contents of the header file in #ifndef and #endif. 
You need to add this whether or not your header file will be referenced by multiple files. 
The general format is this:   
#ifndef <identifier>   
#define <identity>   
......   
......   
#endif <identifier> 
can theoretically be named freely, but each header file has this " ID" should be unique. The naming rule of the logo is generally that the header file name is all uppercase, with underscores before and after, and the "." in the file name is also underlined, such as: stdio.h   
#ifndef _STDIO_H_   
#define _STDIO_H_   
......   
#endif  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324917754&siteId=291194637