Language Selector

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. Its 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.


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 preprocessor 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 preprocessor 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. A macro is a rule that defines how an input sequence (e.g. an identifier) is converted into a replacement output sequence (e.g. some text).

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 My favorite number is: 9.

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:





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:





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 and MYMATH_H is defined. 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.

#pragma once

Many compilers support an simpler, alternate form of header guards using the #pragma directive:

#pragma once serves the same purpose as header guards, and has the added benefit of being shorter and less error-prone. The stdafx.h file that Visual Studio includes in projects that use precompiled headers makes use of this directive in place of header guards.

However, #pragma once is not an official part of the C++ language, and not all compilers support it (although most modern compilers do).

For compatibility purposes, we recommend sticking to header guards.


Header guards are designed to ensure that the contents of a header file is are not copied more than once 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.


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
1.9 -- Header files

118 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


    • 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:



    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?


    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

      [ 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


    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.





      • baldo

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

      • 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. 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


    • 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.


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

  • Anand


  • 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.


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


    #include "NumericOperations.h"

    #ifndef PRINTADD_H
    #define PRINTADD_H

    void PrintAdd(int x, int y);



    #include "NumericOperations.h"


    void PrintSubtract(int x, int y);



    #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.

      • Jimbo

        Does that mean my project won’t be compatible by default? In Visual C++ 2015 the stdafx.h header is by default using the #pragma once instead of #ifndef and I’m calling it in every .cpp file.

  • 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

  • nice article….explained well…But there are 14 directives in C++
    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.ignore(255, ‘n’);
    works fine.

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

  • 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.



    • 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..?



    • 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.


  • 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.

  • techsavvy....aye

    how does the last program in the tutorial work.
    i didn’t understand the main.cpp part.

    • Alex

      main.cpp is just a fragment of a program, not a complete program. The first two lines pull in the contents of add.h and subtract.h.

      What main.cpp does with these isn’t defined in the example above, because it’s not relevant to what I’m trying to explain.

      • techsavvy....aye

        thank u for the reply but could u plz give me the main.cpp portion (entire)
        i couldn’t figure it out myself as i started learning recently.
        Also would u tell me the expected no. of months/days in which i could finish this entire tutorial.

        • Alex

          You could do this:


          I can’t give you an estimate to how long the tutorials will take because I have no idea how fast you read, understand, or remember the content.

  • Odgarig

    Hello, Thank you for the great lessons.I had been doing good with all these great lessons until i got this question in my mind.
    Actually, I’m confused with these sentences >>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.<< These sentences are from "Updating our mymath.h example with header guards" section.

    And the QUESTION is: If after main.cpp #includes add.h, which includes mymath.h MYMATH_H has not been defined.THEN why after main.cpp #includes subtract.h, which #includes mymath.h MYMATH_H has been defined ?
    Shoudn’t both (add.h and subtract.h)have been including MYMATH_H as defined ? (This is bad I’m getting confused again)

    I hope you got the idea.And this is really confusing me.Any answer would be appreciate.THANK YOU AGAIN.

    • Alex

      Remember that when you #include a file, the included file is copied into the includer.

      Therefore, when main.cpp #includes add.h, the contents of add.h are copied into main.cpp. Since add.h #includes mymath.h, the contents of mymath.h are copied into main.cpp.

      Similarly, when main.cpp #includes subtract.h, the contents of subtract.h are copied into main.cpp. Since subtract.h also #includes mymath.h, the contents of mymath.h are copied (again) into main.cpp.

      The end result is that main.cpp ends up with two copies of mymath.h. If mymath.h didn’t have header guards, the compiler would try to compile the contents of mymath.h twice, and this would cause an error.

      However, since mymath.h does have a header guard, here’s what happens:
      * The compiler encounters the contents of mymath.h that were included through add.h. Since MYMATH_H has not been defined, the contents of mymath.h are compiled, and MYMATH_H is defined.
      * The compiler encounters the contents of mymath.h that were included through subtract.h. Since MYMATH_H has been defined, the contents are skipped.

      • Odgarig

        Your answer was really helpful.Thank you.I think "Since MYMATH_H has not been defined, the contents of mymath.h are compiled, and MYMATH_H is defined." this sentence made it clear to me and I think if you add "… and MYMATH_H is defined" this sentence in the above lesson where it needed, it wouldn’t confuse again many people like me.And also should we skip lessons with MOVED marks ? And again thank you.

        • Alex

          Good suggestion. I’ve updated the lesson.

          Don’t skip lessons flagged as moved. Those lessons have been moved from somewhere else and are now in their proper location.

  • Amu

    DO you have similar kind tutorial on mfc?, if so please share, it would be very useful.
    Thanks in advance.

  • Hey Alex, thanks for answering my previous questions. Here is a suggestion for this section. I think you should clearly define what macro is and where it should be used. Both the types of macro are defined (at least the important one "object-like")  but I m still looking for a definition on macro.

    One more:
    #define identifier
    #define identifier substitution_text

    The second form (with substitution text) should be :
    #define identifier “substitution_text”. I can tell this by looking at this line of the example:

    Here you enclosed the substitution text (Alex) with double quotes. Let me know if I m wrong…
    Great tutorial. Thanks again.

    • Alex

      I’ve updated the lesson to better define what a macro is.

      In the provided example, the substitution text was actually text meant to be printed, so it needs to be in double quotes. However, if the substitution text were something else (e.g. an integer) then it would not be.

      I’ve also updated the example to a case where the substitution text is an integer.

  • BobZ

    Hi, Alex

    Avneet’s question above was a good one.  But perhaps I am the only one on this planet who does not know what is an "object" in the C++ programming sense?  I had someone explain it to me a few years ago and I did not get it then, so I guess I need a very patient explanation………  I did a quick search of the word in the previous few lessons and did not see where you define it anywhere?  I hope you do not object to my question.  :-)

    • Alex

      An object in C++ programming generally refers to a self-contained data structure that includes functions that operate on that data.

      But in the context of these macros, the word object has a different meaning. They’re called object-like macros because the identifiers that are defined look like data objects (e.g. constant variables), as opposed to function-like macros, which look like function calls.

      Don’t get too hung up on this, it’s just a name. :)

  • Andy

    Hey Alex,

    I just wanted to tell you that I think you made a typo here: "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)". (It’s in the last paragraph).

    Have a nice summer! 😀

  • BobZ

    Hi, Alex
    Thanks again.  I was struggling with this tutorial but did the quiz without too much difficulty.  I feel like the quiz was easier than the tutorial……It was certainly shorter!

  • liyuan

    I dont understand one thing. If header files only contain declarations why do you need header guards? I’ve tried having multiple lines of declarations of the same function and my code blocks has no problem compiling the code. in the tutorial you gave an example of a header file containing a definition but aren’t definitions supposed to be in cpp files? hope you can clarify :)

    • Alex

      Good question. The short answer is that header files can contain both declarations and definitions, and the compiler will complain if you have more than one definition for an identifier, even if it’s identical to the previous one.

      If your header file contained nothing but pure declarations, then header guards technically wouldn’t be necessary (but I’d still add them anyway for safety).

  • Essi

    Thanks for this nice tutorials.

    I’m using MS Visual Studio 2015, and I followed the codes in this page, but I get the two linking errors LNK1169:"one or more multiply defined symbols found" and also LNK2005: "_main already defined in main.obj".
    I googled the errors but I couldn’t find the solution. Some suggest that this problem may occur when there is function definition in the header file?
    But this also does not work!! :(

    • Alex

      Sounds like you have function main() defined twice, possible in two different files in your project, or possible in a header file that’s being included in multiple places.

      Make sure you have function main() defined in only one code (.cpp) file in your project.

  • Essi

    Thanks for the quick response.

    I faced another error Error C2084: ‘Function already has a body’. However, I fixed the problem.
    The issue is when building a project, it is always better to keep the project name the same as the cpp file that contains the main() function.
    Thanks again. :)

  • Hi Alex,
    You told here :
    << #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. >>
    "tells the compiler" / when #include is a preprocessor command so why tells the compiler,
    doesn’t tell the preprocessor ?!

  • Kevin

    Hey! I made a small program just messing around, and during the last couple lessons I’ve been editing it to make it simpler/easier to read, here it is

    math.h contains

    Anyways, the problem I’m having is when I try to shove playerInput into its own file and put a function prototype, it doesn’t give the inputs (x and y) to main(). It’ll always give me 0 as the output. What am I doing wrong? Does playerInput just have to be within the same file as main()?

    • Alex

      playerInput() can be in a separate file, if you write it correctly. The problem is that you’re using global variables to pass data between functions, which is a bad idea.

      There are ways to fix this so it will do what you want, but honestly, any solution in that regard is putting a band-aid on bad habits.

      You should get rid of x and y as global variables and utilize local variables, parameters, and return values to move the necessary values between the functions.

  • Unknown

    Hello again,
    Now I can’t understand why we #include mymath.h to add.h and subtract.h.
    Why can’t we just #include mymath.h to main.cpp directly?

    Thanks in advance.

    • Alex

      The example is somewhat arbitrary -- there’s no reason add.h and subtract.h need to include mymath.h. But it’s being done to illustrate the larger point around why header guards are useful, and how a header can get included multiple times even if you don’t expect it to be.

      You can include mymath.h directly, but then it would be included in main.cpp 3 times: once directly, once as part of add.h, and once as part of subtract.h.

  • Jim

    It seems to me that a lot of extra work is being done to make header guards and header files and then adding all this to each function including main and make sure all of this is done correctly where needed.

    I think it would be much easier just to copy and paste the function declaration part if every function like, int add (int x, int y), back into add.cpp and make it a prototype with the semicolon after it. Then save it. If you want to use any function like add.cpp in any program you just insert it into the IDE and cut and pasted the prototype section into main.cpp and your done.

    Of course you just need to make it a habit with ever function. Then you can use that function in any program and any number of time you want without a problem.  This seems a lot simpler to me.

    • Alex

      It might seem simpler now, because we are dealing with simple examples. As programs get more complicated, the method you propose above won’t scale.

      I’m not making you do extra work because I want to see you suffer. :) I’m trying to set you up with good habits now so that when we get to more advanced topics and have programs that span multiple files and have many functions, you’ll understand how to write programs that are easily extensible, and so that you can package up things into easily reusable pieces.

  • Stanley Delva

    Can you declare variables in a header file for later use?

    • Alex

      You can define variables in a header, though it might not work like you expect. What actually happens is that when you #include the header file in your .cpp file, all of the lines of the header get copied into the .cpp file. So if you’ve defined any variables in the header, they get copied into the .cpp and treated as if you’d defined them in the .cpp file. If the header is #included in multiple .cpp files, each gets their own copy of the variable (which may or may not cause naming conflicts).

      Defining variables in a header is usually undesirable. IMO, the only variables that you should define in a header are constants that you use in your program.

      It is okay to forward declare variables in a header if that makes sense for what you’re doing (we talk about how to do this in chapter 4).

  • Sharaf

    hey, do you mean
    if i have defined bob then if i use #ifndef it will not print it?

  • Sharaf

    is header guard only for programs which have a muliple file, if not can you make a single program to illustrate the mymath.h, add.h, subtract.h, main.cpp….. or any other explaining the use of header guard… and why you have changed mymath to MYMATH…
    i couldn’t compile the program because i coudn’t make multiple filed program………. i am getting error as “anyname() not found in directory”
    and sorry for this stupid question why you have used a particular use of #ifndef and #define

    • Alex

      Header guards are for header files, regardless of how many files are in your program.

      It’s convention to use all caps for #define values, presumably to differentiate them from variable and function names.

  • Zuy

    Hi Alex , thanks again for the amazing lessons. I have a problem while following the example on header guard above. Here are what I wrote for the whole thing:

    add.h :
    #ifndef ADD_H
    #define ADD_H

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


    add.cpp :
    #include "stdafx.h"
    #include "add.h"

    int add(int x, int y)
        return x + y;

    subtract.h :
    #ifndef SUBTRACT_H
    #define SUBTRACT_H

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


    subtract.cpp :
    #include "stdafx.h"
    #include "subtract.h"

    int subtract(int x, int y)
        return x - y;

    mymath.h :
    #ifndef MYMATH_H
    #define MYMATH_H
    int cardsInDeck()
        return 52;

    main.cpp :
    #include "add.h"
    #include "subtract.h"

    int main()
        return 0;

    When I tried compiling the programme , there are 3 errors:
    -LNK2005    "int __cdecl cardsInDeck(void)" (?cardsInDeck@@YAHXZ) already defined in add.obj    Preprocessor and Header guards    C:\Users\User\Documents\Visual Studio 2015\Projects\Preprocessor and Header guards\Preprocessor and Header guards\subtract.obj    1    
    -LNK2005    "int __cdecl cardsInDeck(void)" (?cardsInDeck@@YAHXZ) already defined in add.obj    Preprocessor and Header guards    C:\Users\User\Documents\Visual Studio 2015\Projects\Preprocessor and Header guards\Preprocessor and Header guards\main.obj    1    
    -LNK1169    one or more multiply defined symbols found    Preprocessor and Header guards    C:\Users\User\Documents\Visual Studio 2015\Projects\Preprocessor and Header guards\Debug\Preprocessor and Header guards.exe    1    

    I am not sure which part is wrong, I tried to follow the example as closely as I could. I’d be very appreciated if you could help me point out the mistake. Thanks again Alex!

    • Alex

      Ah, you’ve encountered a bit of trickiness. Your header guards _ARE_ working properly.

      The problem here is that we’ve defined function cardsInDeck() in the header file. Since mymath.h is #included once in add.cpp and subtract.cpp, each gets a copy of the definition of cardsInDeck(). The compiler is complaining about the fact that the function definition for cardsInDeck() lives in two different places.

      The solution is easy: move the body of cardsInDeck() to a .cpp file (any .cpp file) and leave just the prototype in the header.

  • Zuy

    Hey Alex,
    I’ve created a mymath.cpp file as below :
    #include "stdafx.h"
    #include "mymath.h"
    int cardsInDeck()
        return 52;

    and now mymath.h contains :
    #ifndef MYMATH_H
    #define MYMATH_H
    int cardsInDeck();

    I tried building and it worked but the output was " Press any key to continue" or No output there I guess…

    I’m really confused about the process.. lol

    Thanks again Alex!

    • Alex

      Perfect. Look at the main() function. It does nothing but return 0, so no output.

      You can add whatever you want in main() and make it do something else. But it wasn’t germane to the example.

Leave a Comment

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




nineteen − 15 =