2

I have been reading Zed Shaw's "Learn C The Hard Way". In the 20th chapter, the author creates a header file e.g. headerfile.h and includes the line #ifndef _headerfile_h. I understand the #ifndef directive but not _headerfile_h. Please explain this _headerfile_h or mention any resource to look for it.

#ifndef _headerfile_h
#define _headerfile_h

…other material…

#endif /* _headerfile_h */
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    It's called a "header guard" to prevent it being compiled twice. Within the `#ifndef ... #endif` block there should be `#define _headerfile_h` – Weather Vane Jul 08 '19 at 05:47

2 Answers2

4

It's simply a unique name that will only used by that header, to prevent problems if the header is included twice.

Note that you should not, in general, create function, variable, tag or macro names that start with an underscore. Part of C11 §7.1.3 Reserved identifiers says:

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.

See also:

and probably some others too. A number of those questions have further links to other resources — SO questions and external links.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
3

The directive #ifndef checks if the "argument" is defined as a macro or not. If it's not defined (the n in ifndef stands for "not") then the next block up to the matching #endif is passed on by the preprocessor.

If the macro is defined, then the block is skipped and not passed on to the compiler by the preprocessor.

So what #ifndef _headerfile_h does is check if the symbol _headerfile_h is defined as a macro or not.

From the macro name it seems like this is part of an header include guard.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621