7

Why sometimes I see

#define __Empty_macro__

in C? What is the usage of it? For example:

#ifndef _BUILDIN_H_
#define _BUILDIN_H_

//codes never used _BUILDIN_H_ ...

#endif /* _BUILDIN_H_ */

For example, here is the source code of a shell.

mneri
  • 2,127
  • 2
  • 23
  • 34
Denly
  • 899
  • 1
  • 10
  • 21

3 Answers3

8

Because an "empty macro" still exists and it is possible to check if they exist using #ifdef or #ifndef.

Typically, this behavior is used to prevent multiple copies of the same header being included (aka "include guards", which is what your example is). However, it can also be used to conditionally include certain portions of a program.

Sometimes, macros like NDEBUG or _DEBUG merely being defined can change program output, such as by including more expensive runtime checks which would be undesirable in the final product, but could help track bugs during development.

Custom "empty" defines can be used similarly to include or exclude certain binary functionality from the program build. This could be done for performance (removing logging), security (removing sensitive parts of the program), business reasons (some features might require more expensive versions of the program), and so on.

5

There are different reasons for using them. For example if need to include some library just once. You could define a macro. Then you check if that macro has been defined so you skip the inclusion. And so on.

Here there is an explanation about: inclusion guard

granmirupa
  • 2,780
  • 16
  • 27
4

In the C and C++ programming languages, an #include guard, sometimes called a macro guard, is a particular construct used to avoid the problem of double inclusion when dealing with the include directive. The addition of #include guards to a header file is one way to make that file idempotent. For example, Consider you want to include grandfather.h and father.h header files in child.h file.

File "grandfather.h"

#ifndef GRANDFATHER_H
#define GRANDFATHER_H

struct foo {
   int member;
};

#endif /* GRANDFATHER_H */

File "father.h"

#include "grandfather.h"

File "child.c"

#include "grandfather.h"
#include "father.h"

Here, the first inclusion of "grandfather.h" causes the macro GRANDFATHER_H to be defined. Then, when "child.c" includes "grandfather.h" the second time (as father.h also includes grandfather.h) by including father.h, the #ifndef test returns false, and the preprocessor skips down to the #endif of the file grandfather.h, thus avoiding the second definition of struct foo. And the program compiles correctly.

abhiarora
  • 9,743
  • 5
  • 32
  • 57