jason hong
jason hong

Reputation: 445

Defines inside a C Project

Often we see defines in the .h file like

  #ifndef _XX_H
 #define _XX_
  #ifdef __YY
  #include <yy.h>
 #endif
#endif      

But where does _XX_H got defined? If it''s been defined. Could it be defined in another .h file? Could be defined by the some files not generated by the programmer?

Another in this case if I want to __XX_H in my .h file how do I do that.

#define _XX_H

like that?

Upvotes: 0

Views: 98

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726919

The snippet in your post has two problems with inclusion guards:

  • _XX_H definition is checked, but _XX_ is defined - this is likely a typo - such guard does not "guard" anything. You should fix this to #define _XX_H
  • Definition of __YY inclusion guard is checked outside yy.h - this is a very bad pattern: it is aimed at optimizing inclusions by preventing the opening of the <yy.h> by looking at its private inclusion guard. This practice makes your builds very fragile. If the authors of yy.h decided to guard their includes with _YY_H instead of __YY, the guard inside your header would fail.

Upvotes: 4

sedavidw
sedavidw

Reputation: 11741

You're correct in that it should include the "_H". General form of an include guard:

#ifndef _FILE_H
#define _FILE_H

//INSERT CODE

#endif //_FILE_H

This format allows you to include the header in multiple files without defining/including anything within the header file twice

Upvotes: 4

Related Questions