1.10 — A first look at the preprocessor

The preprocessor is perhaps best thought of as a separate program that runs just before the compiler when you compile your program. When the preprocessor runs, it simply scans through each code file from top to bottom, looking for 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 simply manipulates text before the compiler runs. The output of the preprocessor is then sent to the compiler. Note that the preprocessor does not modify the original code files in any way -- rather, all text changes made by the preprocessor happen temporarily in-memory.


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. You’ll generally use this form when you’re including headers that come with the compiler (e.g. that are part of the C++ standard library).

#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. You’ll generally use this form for including your own header files.

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 (not statements), note that neither form ends with a semicolon.

Object-like macros with substitution text

When 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: any further occurrence of the identifier is removed and replaced by nothing!

This might seem pretty useless, and it is for doing text substitution. However, that’s not what this form of the directive is generally used for. We’ll discuss the uses of this form in just a moment.

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.

Conditional compilation is used quite a bit in the form of header guards. We’ll take a look at those in the next lesson.

Now you might be wondering:

Since we defined PRINT_JOE to be nothing, how come the preprocessor didn’t replace PRINT_JOE in #ifdef PRINT_JOE with nothing? Macros only cause text substitution for normal code. Other preprocessor commands are ignored. Consequently, the PRINT_JOE in #ifdef PRINT_JOE is left alone.

For example:

The scope of defines

Directives are resolved before compilation, from top to bottom on a file-by-file basis. Once the preprocessor has finished, all directives from that file are discarded.

This means that directives are only valid from the point of definition to the end of the file in which they are defined. Directives defined in one code file do not have impact on other code files in the same project.

Consider the following example:



The above program will print:

Not printing!

Even though PRINT was defined in main.cpp, that doesn’t have any impact on anything in function.cpp. This will be of consequence in the next lesson on header guards.

Finally, note that directives defined in a header file can be #included into multiple code files. This provides a way for directives to be defined in one place and used in multiple code files. We’ll see an example of this in the next lesson as well.

1.10a -- Header guards
1.9 -- Header files

98 comments to 1.10 — A first look at the preprocessor

  • ukijo

    where to put this code? on the header file ??

  • Djordje D.

    I have a promblem on a last example (The scope of defines) , I am getting this  log in an output field:

    1>---- Build started: Project: 0110, Configuration: Debug Win32 ----
    1>c:\users\agencija\documents\visual studio 2005\projects\0110\0110\0110.cpp(11) : error C3861: ‘doSomething’: identifier not found
    1>c:\users\agencija\documents\visual studio 2005\projects\0110\0110\function.cpp(13) : fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include "stdafx.h"’ to your source?
    1>Generating Code…
    1>Build log was saved at "file://c:\Users\Agencija\Documents\Visual Studio 2005\Projects\0110\0110\Debug\BuildLog.htm"
    1>0110 - 2 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    What am I doing wrong?

  • Jim Smith

    First of all, thank you for this site! You make the world a better place.

    Now, the boring stuff. This can be ignored by experienced programmers. I was trying to get fancy and created a function called input() that would ask the user for a number and then return that number back to the caller. Then I put this function on a separate file, just as we did with the add() function. To my surprise, the compiler complained about std::cin and std::cout from the input() function despite the fact that I had #include <iostream> in the main.cpp file. I thought the main.cpp file gets compiled first 🙂 Of, course, I put another #include <iostream> in the input.cpp file and everything worked out fine. But I was wondering, isn’t it a waste to use #include <iostream> multiple times? Then I learned about header guards and with a little Google-Fu I even found out about #pragma once, a directive that prevents <iostream> from being included multiple times.

    • Alex

      A few things:
      1) The C++ compiles each file individually. It does not remember anything from files it’s previously compiled. So if you use std::cout in a given file, that file needs to include iostream.
      2) Header guards do _not_ prevent a header from being included into multiple different files. They prevent a header from being included more than once into the same file.

  • trey

    In you example of print, sometimes it really changes the desicision like:

  • JeffFromOhio

    Alex: Hi, not sure if you still maintain this site. When discussing the preprocessor, instead of saying that it makes changes to the text of a file, I think, isn’t it more accurate to say that the preprocessor creates a new temporary file where the contents of the original source file has changes from the preprocessor merged into this ‘working copy’, and then the ‘working copy’ is what actually gets compiled by the compiler, not the original source file?

    The distinction is important because none of the original files (either .cpp or .h files) are ever actually changed. They will be exactly the same after compilation as before, and so this might confuse new programmers.

    • Alex

      Yeah, I can see how this might have been unclear. I’ve updated the lesson text to explicitly indicate that the original code files are not modified. Thanks for the feedback.

  • Jay Ha

    #include "stdafx.h"
    #include <iostream>

    #define anything "hello the world"

    void hi()
        std::cout << "say hi to me" << std::endl;

    int main()

        #ifdef anything
        std::cout << anything << std::endl;

        #endif // anything
    #ifndef myname
    #define myname
    #ifdef myname
        std::cout << "I am Jay " << std::endl;
    #ifndef sayhi

        return 0;

    basically, I understand this lesson.
    I am just wondering whether we are going to have more use of #defines in future lessons. Can’t wait to read more.

    • Alex

      In C++, defines are mostly used for header guards and conditional compilation. I talk about both of these shortly. Beyond that, most of what the preprocessor can do isn’t used, because there are better, safer ways to do the same things.

  • My dear c++ Teacher,
    Please let  me say my problem with
    I save (by Ctrl-s) code of function.cpp and give this name, but when run main.cpp, output is:

    /home/WBEnb0/cc58Mmhf.o: In function `main’:
    prog.cpp:(.text.startup+0x12): undefined reference to `doSomething()’
    collect2: error: ld returned 1 exit status

    What is going wrong?
    With regards and friendship.

    • Alex

      It looks like codechef may be treating each tab as a separate program, rather than as separate files to be compiled into a single program. If that’s actually the case, then it’s not suitable for compiling programs that use multiple files.

  • My dear c++ Teacher,
    Please let me say that term "preprocessor" is confusing with integrated circuit "processor". So I think term "precompiler" is better fit for it.
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me point out that in example:

    color of first and second comments is same to directives. Is it mean something?
    With regards and friendship.

    • Alex

      The preprocessor line comments being brown instead of green is due to a limitation of the syntax highlighter used on this website.

      All comments in the source code are removed before the preprocessor runs, so there’s no difference between a comment on a preprocessor line or elsewhere.

  • maria

    i was trying to compile the same code as your’s but it is not working… shows this error

    g++ -std=c++11 -o main *.cpp                                                                                    
    main.cpp:4:10: error: ‘cout’ in namespace ‘std’ does not name a type                                            
         std::cout << FOO; // This FOO gets replaced with 9 because it’s part of the normal code                    

    #define FOO 9 // Here’s a macro substitution
    int main()

    #ifdef FOO // This FOO does not get replaced because it’s part of another preprocessor directive
        std::cout << FOO; // This FOO gets replaced with 9 because it’s part of the normal code

  • nikos-13

    "When the preprocessor encounters this directive, any further occurrence of ‘identifier’ is replaced by ‘substitution_text’ (excluding use in other preprocessor directives)."
    What do you mean with "(excluding use in other preprocessor directives)" ??????

    And: "when the identifier is encountered by the preprocessor (outside of another preprocessor directive), it is removed and replaced by nothing!"
    What do you mean with "(outside of another preprocessor directive)" ??????

    • Alex

      Preprocessor directives don’t affect other preprocessor directives. So, for example, if you had the following:

      For normal code, any occurrence of FOO (such as the one being std::cout above) would be replaced by 9. However, other preprocessor statements are immune to this text substitution, so the FOO in #ifdef FOO is not replaced.

      I’ve added this bit to the lesson, since it might be helpful for other readers.

  • Anonymous

    Thank you so much Alex, I have learned a lot from your tutorials

  • Ayush Sharma

    The best tutorials I have come across so far…
    My question is do you have similar tutorials for any other language like java or python?
    If yes,please reply and let me know.

  • Daniel

    thanks alex
    i have reached here since 5 days ago (going a bit slow but i test and learn every bit of it) 🙂

    one question i have is:
    1_i heard by some that C++ is the mother language and you can learn others very fast if you learn C++..true??
    2_i have also seen an extension for C++ named Xamarin (spelled correctly?) that makes you to make android apps and im going to buy it but i wonder that how it works…you code in C++ and it converts them to java??  or a java support for C++??

    • Alex

      Many languages that came after C++ use a similar syntax to C++, so once you know C++, it is a lot easier to learn other languages. I don’t know if I’d say you can learn them fast, but certainly a lot faster than trying to learn them from scratch.
      I’ve never heard of Xamarin before, so I can’t comment on how it works.

  • Alexander Kindel

    I guess I can’t reply to a specific comment without an account? Anyway, in reply to the immediately above:

    That makes more sense. To be fair, nowhere else I looked mentioned that caveat either. There’s one more thing that isn’t clear now, though; from the section on object-like macros without substitution text, I got the impression that the fact that they replace later appearances of their identifiers with nothing is what makes them useful for conditional compilation, but since that mechanic doesn’t affect other preprocessor directives, and the only place the macro’s identifier necessarily reappears in that context is inside other preprocessor directives, it seems that it doesn’t in fact come into play at all there. Is that right?

    • Alex

      There are no accounts on this site. All functionality is available to anonymous users. Just click the reply link next to the comment you want to reply to.

      Object-like macros without substitution text are pretty much never used outside of conditional compilation directives (which are exempt from the substitution effects).

      • Alexander Kindel

        Huh, I could have sworn the reply buttons weren’t there last time. They probably were there, but I did look.

        Does that mean that one could also use an object-like macro with substitution text for conditional compilation (even though the substitution text would be pointless) and it would work just the same?

        Thanks for the clarifications! This is a very helpful site.

        • Alex

          I’d never thought to try it before. So I just tried it with Visual Studio 2015, and it does work (though as you note, the substitution text isn’t used in this case).

  • Alexander Kindel

    You say an object-like macro without substitution text replaces each subsequent appearance of its identifier with nothing. I understand this to mean that in the example under "conditional compilation," the preprocessor changes line 3 from


    . That, in turn, suggests that the specific circumstance under which code after #ifdef is compiled is when there is no identifier after the #ifdef. In that case, I would expect it to also be possible to get rid of the identifier myself, so that the code

    would cause the code after the #ifdef to be compiled, but it seems that having an #ifdef without an identifier in the first place isn’t allowed. Is the preprocessor allowed to cause it to happen, but I’m not?

    • Alex

      No. I realize I didn’t mention in the lesson that object-like macros don’t affect other preprocessor directives. I’ve updated the lesson to mention that.

      So when you #define PRINT_JOE, any occurrences of PRINT_JOE outside of preprocessor directives are removed, but any occurrences of PRINT_JOE inside of preprocessor directives (such as #ifdef PRINT_JOE) are left alone.

      If this weren’t the case, #ifdef would be useless.

  • Olivier


    I’m using visual studio 2015 and had some problems with this code.
    Even if I copy pasted it in, it would give 2 errors.

    Could it be that you just have to add ";" after "printing!" and "not printing!" in the function.cpp?


  • Aman


    #include <iostream>

    void doSomething()
    #ifdef PRINT
        std::cout << "Printing!"
    #ifndef PRINT
        std::cout << "Not printing!"


    void doSomething(); // forward declaration for function doSomething()

    int main()
    #define PRINT


        return 0;

    If directives defined in one code can’t be used by other then why didn’t we include iostream directive in the main.cpp as we did in function.cpp?

    • Alex

      main.cpp doesn’t use anything in the iostream header, so it doesn’t need to be included.

      However, if main.cpp did print something using std::cout, it would need to #include iostream itself.

  • Abhishek

    HEY guys, i am unable to get the output for this code. What is wrong? Pls explain.
    Codeblocks in main.cpp

    #define PRINT_JOE

    int main()

    #ifdef PRINT_JOE
    std::cout << "Joe" << endl;

    #ifdef PRINT_BOB
    std::cout << "Bob" << endl;

    return 0;

    I am getting this error

    ||=== Build: Debug in Chapter1.10
    (compiler: GNU GCC Compiler) ===|
    s Folder\C++ Programs Practice\Chapter1.10\main.cpp||   In function ‘int main()’:|
    s Folder\C++ Programs Practice\Chapter1.10\main.cpp|8|  error: ‘endl’ was not declared in this scope|
    s Folder\C++ Programs Practice\Chapter1.10\main.cpp|8|  note: suggested alternative:|
    C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\
    mingw32\4.9.2\include\c++\ostream|564|                  note:   ‘std::endl’|
    ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

  • Strong

    Hi guys . why we #define ADD_H in the following code ? this code is about previous examples . I deleted #define ADD_H and my codes still work , Can you explain exactly what happend when we invoke ( include "add.h") ?

  • Joshua2000B

    Is there a way to set a variable that is available within every function? For example, say I wanted to load a variable from a .txt file and have that variable used within a function that uses that number to produce a new digit? This is basically what I have so far.

    Many File Program.cpp


    • Alex

      Yes, global variables are available to serve this purpose, though most programmers would argue you shouldn’t use them unless necessary. We cover global variables and the reasons they are problematic in chapter 4.

  • Harshul

    Why is their use not recommended, they are fast and capable of doing what small functions are expected to do???

    • Alex

      Function-like macros are full of gotchas and unexpected behavior that that’s avoided by using normal functions, particularly when it comes to side effects.


      Seems harmless, right?

      But if you call it like this:

      You’d expect the result to be 4, but you actually get 6.

      This happens because ++n is copied into the macro before being evaluated, so your output statement becomes “std::cout << (++n) + (++n);" This sort of behavior is avoided using normal functions.

  • Harshul

    Wouldn’t it be a more appropriate define for macro as given by gnu-
    "A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro."

    • Alex

      That definition would be appropriate if macros were strictly substitution-based. But function-like macros do a little more than replacement (even though we don’t recommend their use).

  • Nyap

    I came across this on Stack Overflow:
    "Notably, it completely misses an introduction to the STL and the proper use of it. You barely see std::cout and std::string. There’s no mention of <algorithm> that I could see of and no mention of the <vector> or <deque> or <map> which are the most commonly used containers in C++."
    Whats this? D:

    • Alex

      A professional race car driver might look at a drivers education course and criticise it for not teaching you how to drive race cars. But that’s not really the point, is it?

      Some of these criticisms are fair, and have already been addressed in updates made over the last 5 years. Others (e.g. the omission of parts of the STL) miss the mark a bit. The point of this tutorial isn’t to comprehensively cover every corner of the STL (though I’d like to get there someday) -- it’s to teach you how to use the core language mechanics of C++, so that if you want to learn more about the STL (or anything else that builds upon the core mechanics), you’ll be well set up for doing so!

  • Marius

    How do we pronounce the ‘#’ symbol here?

    • Alex

      It doesn’t really have a canonical name. Most often I hear it called “pound” (in the US), “number sign”, or “hash/hashtag”.

      • Darren

        In the UK it is "hash" or "hashtag" due to Twitter. However, within the preprocessor directives context it is strictly just "hash".

  • Sharaf

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

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

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

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

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

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

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

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

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

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

  • Learner

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

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

  • Anand


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

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

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

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

  • arvind

    Great Article , Thanks Alex

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

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

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

  • 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

    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?

    • Mayur B.

      I’m learning programming for small electronic projects which include micro-controllers, and to me object-like macros w/o substitution text are more frequent than the others.
      Here’s an example.

      in above code, if I don’t want to blow buzzer, then I just comment out the line

      There are may be million examples in every domain, but this is the best one I can think of.
      Thanks, Mayur

      • Mayur B.



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

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

Leave a Comment

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