3.1.4 Safer Header

As mentioned earlier, using a header file is like importing the code from the header file into your program. Just like any C++ program, you cannot define the same function twice, so you need to be careful not to define a function with the same function header as one in the library. What happens if you include the library more than once? You saw in an earlier example where you may accidentally include a standard library more than once, but this didn’t break the code.

Creating Safer Header Files

Importing the same library more than once will actually cause the code to fail. While end users of the library may not specify to import the exact same library twice, some libraries may still get imported twice since one library may use another library. A good example of this is the iostream library’s use of the string library. If you didn’t know that the iostream library included the string library, you may end up importing the string library a second time.

Fortunately, there is a process that you can use in C++ to protect your code from multiple imports.

Inclusion Guards

C++ has a set of terms collectively known as inclusion guards that are used to protect against multiple inclusions. You will see 3 basic commands in libraries.

  • #ifndef tokenName - Checks to see if tokenName has been defined. If it hasn’t, then the program continues.

  • #define tokenName - Creates a token and executes the block of code.

  • #endif - Ends the if block. If the token was previously defined, the program will skip ahead to this point. If a define was used, it will end the definition block here.

The token name can be anything but is typically something similar to the header file name.

These safeguards only need to be included for the header file and should enclose the entire code. Take a look at the example below for the split.h file:

#ifndef _split_h
#define _split_h

#include <string>
#include <vector>

using  namespace std;

vector<string> splitline(string input, char delimiter = ' ');

#endif

Notice in the example that the token was named _split_h, but it could be named anything.

In plain English, the flow of this program is to say, if _split_h has not yet been defined, define it now. If it has been defined, skip to the end of the file and do nothing.

As you play around with the example below, try commenting out the #ifndef, #define, and #endif statements to see what happens.

Last updated