Header guards in C++ and C

The FILENAME_H is a convention. If you really wanted, you could use #ifndef FLUFFY_KITTENS as a header guard (provided it was not defined anywhere else), but that would be a tricky bug if you defined it somewhere else, say as the number of kittens for something or other.

In the header file add.h the declarations are literally between #ifndef and #endif.

#ifndef ADD_H
#define ADD_H

#include "mymath.h"
int add(int x, int y);

#endif

Finally, int main() shouldn’t be in a header file. It should always be in a .cpp file.

To clear it up:

#ifndef ADD_H basically means “if ADD_H has not been #defined in the file or in an included file, then compile the code between #ifndef and #endif directives”. So if you try to #include "add.h" more than once in a .cpp file, the compiler will see what the ADD_H was already #defined and will ignore the code between #ifndef and #endif. Header guards only prevent a header file from being included multiple times in the same .cpp file. Header guards don’t prevent other .cpp files from including the header file. But all .cpp files can include the guarded header file only once.

Leave a Comment