Multiple inclusion of header file c++

Using "include guards" (Wikipedia link)

#ifndef MYHEADER_H
#define MYHEADER_H

// header file contents go here...

#endif // MYHEADER_H

This is idiomatic code, easily recognizable by any seasoned C and C++ programmer. Change MYHEADER_H to something specific to you, for example if the header defines a class named CustomerAccount, you can call the guard CUSTOMERACCOUNT_H.


In your specific case, have a separate header/source file for each class. The header file for the Z class will have an include guard:

#ifndef Z_H
#define Z_H

// Code of Z class

#endif Z_H

Now, the headers of both X and Y can include z.h safely - it will only really be included once in a .cpp file that includes both x.h and y.h and no duplication will occur.

Always keep in mind that in C and C++ what's really gets compiled are the source (.c or .cpp) files, not the header files. The header files are just "copy-pasted" by the preprocessor into the sources files that include them.


You can also use #pragma once preprocessor directive in your header files. (There's no need to bother about #ifndef, #define, #endif).


You use what are called include guards or header guards. They go something like this:

// within some_header.h
#ifndef SOME_HEADER_H
#define SOME_HEADER_H

// stuff goes here

#endif

Essentially, the first time around the macro hasn't been defined so everything inside is included. However, after the first time subsequent includes will have no effect.

The naming scheme, like all naming schemes, is completely arbitrary and up to you. I like to include the file name as a minimum, as I did above, in that fashion. I also include namespaces and project names in my real projects.

There are a couple of things to watch out for. You might be tempted to do things like this:

#define _SOME_HEADER_H__

To obfuscate it a bit. However, names that begin with an underscore followed by a capital letter, or contain double-underscores are reserved identifiers, and you cannot use them.

Tags:

C++