Search

Meta

1.10 — A first look at the preprocessor and header guards

The preprocessor is perhaps best thought of as a separate program that runs just before the compiler when you compile your program. It’s purpose is to process directives. Directives are specific instructions that start with a # symbol and end with a newline (NOT a semicolon). There are several different types of directives, which we will cover below. The preprocessor is not smart -- it does not understand C++ syntax; rather, it manipulates text before the compiler runs.

Includes

You’ve already seen the #include directive in action. When you #include a file, the preprocessor copies the contents of the included file into the including file at the point of the #include directive. This is useful when you have information that needs to be included in multiple places (as forward declarations often are).

The #include command has two forms:

#include <filename> tells the compiler to look for the file in a special place defined by the operating system where header files for the C++ runtime library are held.

#include "filename" tells the compiler to look for the file in directory containing the source file doing the #include. If it doesn’t find the header file there, it will check any other include paths that you’ve specified as part of your compiler/IDE settings. That failing, it will act identically to the angled brackets case.

Macro defines

The #define directive can be used to create a macro. There are two basic types of macros: object-like macros, and function-like macros.

Function-like macros act like functions, and serve a similar purpose. We will not discuss them, because their use is generally considered dangerous, and almost anything they can do can be done by an (inline) function.

Object-like macros can be defined in one of two ways:

#define identifier
#define identifier substitution_text

The top definition has no substitution text, whereas the bottom one does. Because these are preprocessor declarations, note that neither form ends with a semicolon.

Object-like macros with substitution text

Whenever the preprocessor encounters this directive, any further occurrence of ‘identifier’ is replaced by ‘substitution_text’. The identifier is traditionally typed in all capital letters, using underscores to represent spaces.

Consider the following snippet:

The preprocessor converts this into the following:

Which, when run, prints the output Hello, Alex.

We discuss this case (and why you shouldn’t use it) in more detail in section 2.8 -- Literals, symbolic constants, and const variables.

Object-like macros without substitution text

Object-like macros can also be defined without substitution text.

For example:

Macros of this form work like you might expect: when the identifier is encountered by the preprocessor, it is removed and replaced by nothing!

While this might seem useless, it’s actually used more often than the form with substitution text. We’ll discuss why in the next section, on conditional compilation.

Unlike object-like macros with substitution text, macros of this form are generally considered acceptable to use.

Conditional compilation

The conditional compilation preprocessor directives allow you to specify under what conditions something will or won’t compile. The only conditional compilation directives we are going to cover in this section are #ifdef, #ifndef, and #endif.

The #ifdef preprocessor directive allow the preprocessor to check whether a value has been previously #defined. If so, the code between the #ifdef and corresponding #endif is compiled. If not, the code is ignored.

Consider the following snippet of code:

Because PRINT_JOE has been #defined, the line cout << "Joe" << endl; will be compiled. Because PRINT_BOB has not been #defined, the line cout << "Bob" << endl; will not be compiled.

#ifndef is the opposite of #ifdef, in that it allows you to check whether a name has NOT been defined yet.

This program prints “Bob”, because PRINT_BOB was never #defined.

Header guards

Because header files can include other header files, it is possible to end up in the situation where a header file gets included multiple times into the same source file. For example, consider the following program:

mymath.h:

add.h:

subtract.h:

main.cpp:

When we include add.h, it brings in both mymath.h and the prototype for add(). When we include subtract.h, it brings in both mymath.h (again) and the prototype for subtract(). Consequently, the contents of mymath.h will have been included twice in main.cpp, which would cause the compiler to complain about cardsInDeck() being defined twice in the same place.

To prevent this from happening, we use header guards, which are conditional compilation directives that take the following form:

When this header is included, the first thing it does is check whether SOME_UNIQUE_NAME_HERE has been previously defined. If this is the first time we’ve included the header, SOME_UNIQUE_NAME_HERE will not have been defined. Consequently, it #defines SOME_UNIQUE_NAME_HERE and includes the contents of the file. If we’ve included the header before, SOME_UNIQUE_NAME_HERE will already have been defined from the first time the contents of the header were included. Consequently, the entire header will be ignored.

All of your header files should have header guards on them. SOME_UNIQUE_NAME_HERE can be any name you want, but typically the name of the header file with a _H appended to it is used. For example, add.h would have the header guard:

Even the standard library includes use header guards. If you were to take a look at the iostream header file from Visual Studio 2005 Express, you would see:

Updating our mymath.h example with header guards

Let’s return to the mymath.h example, as we last saw it:

mymath.h:

add.h:

subtract.h:

main.cpp:

To prevent cardsInDeck() being included twice, we can add header guards to mymath.h.

mymath.h with header guards:

Now, main.cpp #includes add.h, which #includes mymath.h. Since MYMATH_H has not been defined yet, the contents of mymath.h (including cardsInDeck()) are pulled in. main.cpp then #includes subtract.h, which #includes mymath.h. Since MYMATH_H has now been defined, the contents of mymath.h are skipped.

By adding the header guard, we’ve ensured that the contents of mymath.h are only included once in main.cpp.

For good form, we should also add header guards to add.h and subtract.h.

To summarize, header guards are designed to ensure that the contents of a header file is are not copied more than into any single file (to prevent duplicate definitions). However, header guards do not prevent the contents of a header file from being copied (once) into multiple different project files (such as add.h and subtract.h in the example above). This is a good thing, because we often need to reference the contents of a header from different project files.

Quiz

1) Using the mymath.h example above, add header guards to files add.h and subtract.h.

Quiz Answers

1) Show Solution

1.10a -- How to design your first programs
Index
1.9 -- Header files

71 comments to 1.10 — A first look at the preprocessor and header guards

  • GovZ

    Hello guys,

    I just wanted to ask if you have enough room for :

    #if defined(macro_name) || defined (macro_name2)

    in this tutorial :) I use this quite a lot in coding. Is this a part of the standard by the way?

    I have read chapter 0 up to this part and plan to read more. Thanks and more power :)

  • GovZ, as far as I know, that is an official part of the preprocessor. You should also be able to use && to test whether multiple symbols are defined at the same time:

    #if defined (symbol_a) && defined (symbol_b)

    I didn’t cover these specific concepts in this tutorial because I don’t even cover what the || and && symbols mean until section 3.6. This is just supposed to be a quick introduction, not a full preprocessor tutorial. :)

    There are quite a few other neat things the preprocessor can do that I don’t (and don’t plan to) cover in this tutorial. If you are interested in learning more, there are quite a few preprocessor documents that are publicly available. Here’s one.

  • billerr

    This might be a dumb question, but what exactly is the purpose of:

    #define [identifier]

    i.e. a #define without any replacement?

    Is it useful mostly in header guards?

  • Jason

    I’m not absolutely sure but from what I’ve read here and a book I have, I believe you are correct about it only being for the header guards when there is no replacement.

  • Billerr, You can use such defines for several reasons. Header guards are the primary one. However, it can be useful to define code that only executes when certain #defines have been set. For example, you might do something like this:

    This would only print out nDebugVariable if the program was compiled with the _DEBUG symbol #defined. You might turn this symbol on when compiling a version for development or testing, but turn it off for the release version.

    In a game I wrote, I used a #define to toggle whether the game generated random dungeons (for the release version) or a special debug level (for testing/development). I could toggle between the two by commenting/uncommenting the #define and recompiling.

  • David

    I have a quick question… what is the benefit of using define as opposed to simply initilializing the variable?

    What is the difference between

    and

    • Personally I don’t think there is any reason to use #define this way.

      The only place I use #defines is when #defining symbols to use with #ifdef or #ifndef. You can’t use regular variables for those.

  • Ok the coding you provided for the header guard is going to be VERY helpful. Thanks for that.

  • arvind

    Great Article , Thanks Alex

  • adam

    Why can’t you make your whole program in a header file then just have #include “headerfile.h” in the main.cpp and compile? What can and can’t you put in a header file instead of a .cpp file?

    • You can put almost anything in a header file (there are a few exceptions). Thus, you could write your whole program in a header file and #include it into a .cpp, but if you’re going to do that, why not just skip the header file and put the code in the .cpp in the first place?

  • Ray

    I have a question about header guards…borrowing from the above examples if we define:

    add.h

    subtract.h

    and with main.cpp including both:

    won’t we still have the exact same problem, ie add.h and subtract.h both still bring in a copy of myMath.h and the compiler will still complain?

    Thanks,
    Ray

    PS-Thanks for putting this tutorial up, its easily the best I’ve seen on the web

    • Ray

      Never mind i just figured it out…if we use the header guards for every header, in the above example this will include the myMath.h, then when we try to bring in the myMath.h headera second time, MYMATH_H will already be defined (from the first time it was brought in) and the #ifndef statement will not allow for whatever is in myMath.h to be brought in a second time…thats pretty neat.

      Thanks again
      Ray

      [ You got it. -Alex ]

      • Noha

        I just paid attention that your question is close to the question I posted.
        You say “#ifndef statement will not allow for whatever is in myMath.h to be brought in a second time”, you mean that #ifndef MYMATH_H is needed before every #include of add.h and subtract.h?

        • Matt

          The idea is that myMath.h would have a header guard of MYMATH_H, after the first include it would define MYMATH_H and allow the first myMath.h to compile. When it was included the second time MYMATH_H would already be defined from the first call to myMath.h, so it would not compile the second instance of the include.

          tl;dr: The header guard for myMath.h (MYMATH_H) is not needed in add.h or subract.h, it’s needed in myMath.h

  • csvan

    Alex,

    I think it would be very helpful to add a concrete example of header guards in action at the end of this page, based on the headers you previously declared. As this is a somewhat confusing concept depending on how you approach it, having a concrete, documented example would drive through a very forceful explanation.

    Thanks for all your hard work!

  • Noha

    Hi Alex,
    In the example you gave about #include “add.h” and #include “subtract.h”, where we use #ifdef/#ifndef and #andif?
    I guess it should be in main.cpp but don’t know where exactly and how :-/

    • Cooper

      Thanks, Alex! your site is a real help! I wrote a sample temperature converter program with the site’s help!

      Noha, will this help?

    • Alex

      I’ve added this as a quiz question, along with an answer.

      You don’t need to use header guards in .cpp files since they only get compiled/included once as part of your project.

  • Prayrit

    I really don’t understand the header guard example given here. Would the mymath.h have to be taken out of the add and subtract headers, and then put into the main class with another header guard?

    • Prayrit

      Actually I think I got it. Tell me if I’m right.

      mymath.h

      add.h

      subtract.h

      main.cpp

      • baldo

        Yes you got it. This should be the full example for header guards.

      • Rukshan

        Hi,

        Would you kindly write “// your declarations here” part to make it clear. Because I still don’t get the use of “mymath.h” here. Thanks a lot.

      • Rukshan

        Would you kindly write “// your declarations here” part to make it clear. Because I still don’t get the use of “mymath.h” here.

        • Trophy

          Wouldn’t you not need to add the header guards in add.h and subtract.h since the issue is with mymath.h being called twice and not the other two? Or is this just good form?

          • Alex

            In this example, if you omitted the header guards for add.h and subtract.h, it would work anyway because add.h and subtract.h are only being included once. But you really should include header guards for them anyway, because it’s good form. They might get included again later.

  • William

    First, thank you so much, Alex for your excellent tutorial. Having previously been a developer in Assembler, COBOL and C from the decade of the 80’s (left the field in 1990), I can truly appreciate the hard work and excellence you have shared with us all. I find your sight so far to be a wonderful opportunity for me to once again explore the world of programming thru C++.

    My question:
    These last two entries by baldo and Prayrit, baldo indicates that Prayrit’s code should be the full example for header guards. Since you did not reply, I assume you do agree.

    I also take note of your explanation that the compiler will check the function prototypes that have been declared via the add.h and subtract.h #includes against the function calls within the source code to resolve any syntactical errors and it will be the job of the linker to ensure that all the function calls are eventually defined.

    Having said all that, I am not quite sure of the purpose of ‘mymath.h’. The comment in the header file says “// your declarations here”. Is it additional math declarations (eg. division() or multiplication()prototypes)or was it supposed to be the ‘definitions’ for the add() and subtract() functions. I assumed it to be the latter.

    If mymath.h does in this particular case contain the definitions for add() and subtract(), then when it compiles, wouldn’t the compiler not only insert the add() and subtract() function prototypes for declaration within main.cpp but because of the #include of mymath.h within the add.h and subtract.h files, also insert the function definitions of add() and subtract() I assume to be located therin, thereby causing compiling errors?

    Finally, if mymath.h does not contain the definitions, then where are the definitions in this case, and what is mymath.h doing?

    • Alex

      As originally written, mymath.h was intended to be a placeholder for any header file full of mathematical functions. Doesn’t really matter what they are.

      Since this has seemed to cause some bit of confusion, I’ve updated mymath.h to include the definition for a single function. Even though that function isn’t used, it illustrates the general principle better than before.

  • iamone

    Hey Alex great tutorial!
    i was just wondering why #define Print_joe
    was not just #define joe?
    Doesn’t the word Print throw the whole thing off?
    This question has been really bugging me, any answer would be appreciated

    THANKS!

    • Alex

      Your #define symbols can be whatever you like so long as they follow the normal identifier naming rules. There’s no difference between #define PRINT_JOE and #define JOE and anything else. The word PRINT is meaningless in this context except maybe as a note to the reader.

  • retro-starr

    Is there anything wrong with typing the headers in lowercase and with spaces (I still use underscores though)? I tested it out earlier when I was making another program that used a header and it still worked. If there’s nothing wrong, I stylistically like the lowercase.

    • Alex

      There’s nothing syntactically wrong (it will work fine), but convention specifies that #defined values are done in upper case with underscores. It’s up to you if you want to follow convention.

  • this is just awesome teacher…made programming lot easier..thank u fellows..!

  • I’m confused, how does it know if the header has already been declared?
    For example, if it says

    in the header file, how does it know if add.h is declared since they are not the same?

    • Okay never mind. Correct me if I’m wrong:
      All the header files will have

      so that if the header is not included, then SOME_UNIQUE_NAME_HERE will not have been defined.
      “Your declarations here” will be the “include”‘s of headers, and “stuff” should be the code of the header? Thanks.

      • Alex

        Right, if the header hasn’t been included yet, then SOME_UNIQUE_NAME_HERE will not have been defined.

        I don’t know what //stuff is supposed to be. There should be nothing after the end of the header guard (the #endif declaration).

  • David

    I love this tutorial!!!

  • Eric

    I guess my question is: why would a header file need to include a different header file if all header files contain are declarations? Is this something you only encounter once you are writing bigger programs? I understand including header files in places where you are using functions defined in external files to avoid writing a ton of forward declarations, but can someone give me an example that wouldn’t be completely over my head of a header needing to include another header? Thanks!

    • Alex

      This is a great question. It’s actually _very_ common for header files to include other header files.

      You’re correct that header files typically only include declarations. At this point in the tutorials, you’ve only seen one type of declaration: function declarations. However, there are other kinds of declarations (like types and classes) that also live in header files.

      Probably the most common example is with strings. A string is a sequence of characters, like “Hello, world!” or “abcdefg”. C++ doesn’t include very good built-in support for working with strings. The C++ standard library comes with a header file named “string” that includes declarations for a class called “string” that makes it much easier to work with strings.

      So if you want to use std::string (e.g. as a function parameter, or return type), you need to include the string header.

      e.g.

      Even though we haven’t discussed classes or std::string yet, hopefully this makes sense.

  • Anand

    VERY NICE MATERIAL, LEARNED AND PERFORMED IN FIRST ATTEMPT. THANKS.

  • alienbeliever

    This tutorial is so well structured and understandable that it blows my mind. Thanks A LOT. It´s an outstanding work of love. KUDOS!

  • lackadaisy

    I just wanted to leave a note saying this is the most amazing tutorial ever. I hated programming but I think I might start liking it quite a bit now because I finally understand it!

  • YamNahar

    At this step
    #define MY_NAME “Alex”
    cout << "Hello, " << MY_NAME << endl;
    i get 2 errors:
    error C2143: syntax error : missing ';' before '<<'
    error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
    what's wrong? I did something wrong, or was something wrong?

  • Maverick95

    I’m failing to see why I need to use header guards with the IDE that I’m using.
    The code below I’ve used in Microsoft Visual C++ 2010 Express and it compiles without any complaints or errors.

    NumericOperations.h

    int add(int x, int y);
    int subtract(int x, int y);

    PrintAdd.h

    #include "NumericOperations.h"

    #ifndef PRINTADD_H
    #define PRINTADD_H

    void PrintAdd(int x, int y);

    #endif

    PrintSubtract.h

    #include "NumericOperations.h"

    #ifndef PRINTSUBTRACT_H
    #define PRINTSUBTRACT_H

    void PrintSubtract(int x, int y);

    #endif

    HeaderGuardTest.cpp

    #include "stdafx.h"
    #include "PrintAdd.h"
    #include "PrintSubtract.h"
    #include "KeyFunctions.h"

    I should note that all the functions above have been defined in .cpp files.

    My code compiles successfully, but I have included NumericOperations.h twice. Shouldn’t this give me an error?

    • The #ifndef ensures that everything required is initialized once and no more. When you load it the second time, the compiler sees that the variables and whatnot have been declared, so it does nothing.

  • Learner

    #include directives like these are also valid:
    #include “dir/file.h”
    #include “../file.h”

  • dice3000

    I believe that [ #pragma once ] serves the same purpose as header guards

    • Alex

      It does, on compilers that support it.

      The problem is that #pragma once isn’t officially a part of the language, and not all compilers support it (even though many modern ones do). Google’s C++ style guide explicitly tells Google developers not to use #pragma once, so we’re following suit here and not recommending its use.

  • Thanks so much for these tutorials. Wish I had found them years ago. So many basic things that I needed to understand the C++ examples I was reading at the time.

    You present at a good level of detail-enough examples, but not too long.

  • rdewji

    When creating header files, you can add them to the “source files” folder, or the “header files” folder (by right-clicking on the respective folders). Other than organization (in that all the header files should be in the “header files” folder), is there any reason to choose one or the other? The first question that comes to my mind is whether it affects the speed of the program in any way. (Or even if so, would it only affect the speed of compiling, and not of running the program?)

  • legalize

    I really wish this first introduction to the preprocessor would not show examples of using a macro to define a constant. We want new programmers in C++ to learn good habits from the beginning and they are just going to be confused when we show them creating constants with macros and then tell them not to do that. The tutorials here should always represent the best way to do something in C++.

    The best uses for macros have been severely narrowed for a long time in C++ and we shouldn’t show them bad habits.

    • Dashij

      You confused me already with that comment.

      Thing is, I don’t even know what I’m confused about and this is really confusing.

    • Alex

      I agree. I’ve moved the stuff about using #define to define symbolic constants out of this lesson, and into another lesson where I can talk a little more about why it’s bad, and more importantly, what should be used instead.

  • Ieinstein

    HI Alex. Thanks for the good stuff, you are a great teacher. But this topic headers is really confusing. I think it will be perfect to include a typical example. For all the other guys who seem not to understand this Header stuff. please try this link as well. Maybe it might help

    http://faculty.cs.niu.edu/~mcmahon/CS241/c241man/node90.html

  • nice article….explained well…But there are 14 directives in C++
    1-#define
    2-#elif
    3-#elifdef
    4-#elifndef
    5-#else
    6-#endif
    7-#error
    8-#if
    9-#ifdef
    10-#ifndef
    11-#include
    12-#line
    13-#pragma
    14-#undef
    You have written about few of them.What about others?

    • Alex

      It’s an intro lesson, so I’ve opted not to be comprehensive here in the interest of having the lesson not be overly-long. I’ll take a note that we could use a more comprehensive lesson on the preprocessor. In the meantime, there’s plenty of reference material available on the internet that can explain these things. Once you understand how the preprocessor works and some of it’s basic functions, picking up the other directives shouldn’t be too much of an issue.

  • Paras

    Hi Alex.Thanks for your wonderful lessons. I am very new to programming, I hope I am asking the right question. This is the code I was practising. Here system (“paused”); does not work for some reason. It just blinks and goes away but if I use
    cin.clear();
    cin.ignore(255, ‘n’);
    cig.get();
    works fine.

    Would you please don’t mind to explain? Sorry for the bad English too :-(
    Thanks

  • Alex

    The cin method clears out any queued input, then waits for the user to press a key before proceeding.

    The method of using system(“pause”) (no d on the end of pause) makes a call to the operating system to run the pause executable (if you open a command prompt on Windows, you can type “pause” (no quotes) and see it execute).

    I recommend the cin method because it will work on any operating system.

  • elRaimundo

    Hi and first of all,
    thanks for the great tutorial!
    I have run into a problem trying to compile my project if I add the following preprocessor directives:

    I get the following error in eclipse cdt on the first call to std::cout (I hope I'm using the correct terminology here):
    error: no type named 'cout' in namespace 'std'
    <iostream> is clearly included and I get no complaints about std::cout when its used later in main,
    so what am I missing here?

    • Alex

      The problem here is that lines 5 and 9 are outside of a function, so your compiler is confused because you’re declaring statements somewhere you aren’t supposed to.

      Try copying lines 4 through 10 into your main() function (or another function that main() calls) and it should work fine.

  • Daniel

    Hello all,

    I have tried both tying out and simply copying the text from the example, I keep getting an error message…

    MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
    1>C:\Work\C++\main\Debug\main.exe : fatal error LNK1120: 1 unresolved externals

    To me it seems for some reason it is unable to find the header files, I created them in the same was as I have in past tutorials which all worked. They are visible in the browser under Header files.

    Any help would be appreciated.

    regards

    Daniel

    • Alex

      Looks like it can’t find your main() function. Make sure you have a main function, and that it’s in lower case letters.

      If it still doesn’t work, try creating a new console project.

  • Daniel

    Ok, I added an int main() AND #include "stdafx.h" i think before I was doing either or.

    Silly question…

    For the example you have given to be ran correctly it shouldn't read out anything to the console as nowhere in the code does it have a cout <<.

    It now simply runs without throwing an error at me and asks for the user to press button to continue..?

    Regards

    Daniel

    • Alex

      I’m not sure what you’re actually trying to run. The above code bits are just snippets of programs, not full programs.

      If your program doesn’t use cout, then nothing will be written to the console.

  • Daniel

    I managed to get it working,

    for some reason I am yet to figure out it wouldn't let me cout without throwing a wobbler.

    Tried it after work and it seems to cout ok :D.

    Daniel

  • Chris

    You’ve already seen the #include directive in action. When you #include a file, "the preprocessor copies the contents of the included file are copied into the including file at the point of the #include directive". This is useful when you have information that needs to be included in multiple places (as forward declarations often are).

    Please review the part of the sentence above that I’ve highlighted with quotations.

    I think it should read:
    the preprocessor copies the contents of the included file into the including file at the point of the #include directive.

Leave a Comment

  

  

  

8 − six =

Put C++ code inside [code][/code] tags to use the syntax highlighter