Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

2.1. Making Sure a Header File Gets Included Only Once

Problem

You have a header file that is included by several other files. You want to make sure the preprocessor scans the declarations in the header file no more than once.

Solution

#define a macro in your header file, and include only the contents of the header file if the macro hasn’t already been defined. You can use this combination of the #ifndef, #define, and #endif preprocessor directives, as I did in Example 2-1:

#ifndef MYCLASS_H_  _ // #include guards
#define MYCLASS_H_  _

// Put everything here...

#endif // MYCLASS_H_  _

When the preprocessor scans this header file, one of the first things it will encounter is the #ifndef directive and the symbol that follows. #ifndef tells the preprocessor to continue processing on the next line only if the symbol MYCLASS_H_ _ is not already defined. If it is already defined, then the preprocessor should skip to the closing #endif. The line following #ifndef defines MYCLASS_H_ _, so if this file is scanned by the preprocessor twice in the same compilation, the second time MYCLASS_H_ _ is defined. By placing all of your code in between the #ifndef and #endif, you ensure that it is only read once during the compilation process.

Discussion

If you don’t use this technique, which is called using include guards , you’ve probably already seen “symbol already defined” compilation errors that result from not taking a protective measure against multiple definitions. C++ does not allow you to define ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page