In C and C ++, why is every .h file usually surrounded by #ifndef #define #endif directives?

Why does every .h file start with # ifndef #define #endif? We can compile a program without these directives.

+7
c ++ c c-preprocessor include-guards
source share
5 answers

This is the so-called "enable security". The goal is to prevent the file from being parsed repeatedly if it is included several times.

+14
source share

It prevents multiple inclusions of a single file. The same can be done using

#pragma once 

but these #ifndefs are standardly supported by each compiler.

+4
source share

It is called the inclusion guard. You can write without them until you start writing large programs and find out that you need to include the same .h file more than once, directly or indirectly, from the .c file. Then without turning on the defenders you will get several definition errors, but with them the contents of the header are analyzed only once and skips all subsequent times, avoiding these errors. It is good practice to always use them.

+3
source share

If I understand correctly, you want to know if, in the absence of security guards, he can include the header file several times, causing an error or dangerous behavior. This is after excluding several definitions, etc.

Imagine a malicious programmer with no security devices in the header file. Its header file defines one macro, SZ , which is the size you use for your statically distributed arrays. The programmer could write his header file as follows:

 #ifndef SZ #define SZ 1024 #else #if SZ == 1024 #undef SZ #define SZ 128 #else #error "You can include me no more than two times!" #endif #endif 

Now, if you include the header file once, you get SZ equal to 1024. If you include it twice, SZ will be 128. Of course, most real-world programmers are not malicious, and no one actually writes the code as described above.

Note that the C standard allows assert.h be #include d more than once with different behaviors, depending on whether NDEBUG defined when NDEBUG is included. Therefore, assert.h cannot include protection. This is a function, not an error.

+1
source share

If the header file contains a type definition

  int i; 
than than, being turned on several times without protection, it produces a compilation error.
ifndef checks that some preprocessor variable is not defined (and this is not the case for the first time), and then defines it explicitly to avoid re-capture. In MSVC you can also use
  #pragma once 
instead of ifndef .
-one
source share

All Articles