1.9 — Header files

Headers, and their purpose

As programs grow larger and larger (and include more files), it becomes increasingly tedious to have to forward declare every function you want to use that lives in a different file. Wouldn’t it be nice if you could put all your declarations in one place?

C++ code files (with a .cpp extension) are not the only files commonly seen in C++ programs. The other type of file is called a header file, sometimes known as an include file. Header files usually have a .h extension, but you will sometimes see them with a .hpp extension or no extension at all. The purpose of a header file is to hold declarations for other files to use.

Using standard library header files

Consider the following program:

This program prints “Hello, world!” to the console using cout. However, this program never defines cout, so how does the compiler know what cout is? The answer is that cout has been declared in a header file called “iostream”. When we use the line #include <iostream>, we’re requesting that all of the content from the header file named “iostream” be copied into the including file. That makes the content from the header file available for use in our code file.

Keep in mind that header files typically only contain declarations. They do not define how something is implemented. So if cout is only declared in the “iostream” header file, where is it actually defined? It is implemented in the C++ runtime support library, which is automatically linked into your program during the link phase.

Consider what would happen if the iostream header did not exist. Wherever you used std::cout, you would have to manually copy in all of the declarations related to std::cout into the top of each file that used it! This would require knowledge of what’s relevant and what’s not. It’s much easier to just #include iostream!

Writing your own header files

Now let’s go back to the example we were discussing in a previous lesson. When we left off, we had two files, add.cpp and main.cpp, that looked like this:



(If you’re recreating this example from scratch, don’t forget to add add.cpp to your project so it gets compiled in).

We used a forward declaration so that the compiler would know what “add” was when compiling main.cpp. As previously mentioned, writing forward declarations for every function you want to use that lives in another file can get tedious quickly.

Header files can relieve us of this burden. A header file only has to be written once, and it can be included in as many files as needed. This also helps with maintenance by minimizing the number of changes that need to be made if a function prototype ever changes (eg. by adding a new parameter).

Writing our own header files is surprisingly easy. Header files consist of two parts.

The first part is called a header guard, which is discussed in the next lesson (on the preprocessor). Header guards prevent a given header file from being #included more than once in the same file.

The second part is the actual content of the .h file, which should be the declarations for all of the functions we want other files to be able to see. Our header files should all have a .h extension, so we’ll call our new header file add.h:


In order to use this header file in main.cpp, we have to include it.

main.cpp that includes add.h:

add.cpp stays the same:

When the compiler compiles the #include "add.h" line, it copies the contents of add.h into the current file at that point. Because our add.h contains a function prototype for add(), this prototype is now being used as a forward declaration of add()!

Consequently, our program will compile and link correctly.

Note: When you #include a file, the entire content of the included file is inserted at the point of inclusion.

If you get a compiler error about add.h not being found, make sure the file is really named add.h. Depending on how you created and named it, it’s possible the file could have been named something like “add” (no extension) or “add.h.txt” or “add.hpp”.

If you get a linker error about add() not being defined, make sure you’ve included add.cpp in your project so it compiles properly!

Angled brackets vs quotes

You’re probably curious why we use angled brackets for iostream, and double quotes for add.h. The answer is that angled brackets are used to tell the compiler that we are including a header file that was included with the compiler, so it should look for that header file in the system directories. The double-quotes tell the compiler that this is a header file we are supplying, so it should look for that header file in the current directory containing our source code first. 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 fall back to checking the system directories.

Rule: Use angled brackets to include header files that come with the compiler. Use double quotes to include any other header files.

Header files may include other header files. However, you should never rely on this. Always #include all of the header files you need to use from each .cpp file.

Rule: Each .cpp file should explicitly #include all of the header files it needs to compile.

Why doesn’t iostream have a .h extension?

Another commonly asked question is “why doesn’t iostream (or any of the other standard library header files) have a .h extension?”. The answer is, because iostream.h is a different header file than iostream is! To explain requires a very short history lesson.

When C++ was first created, all of the files in the standard runtime library ended in .h. Life was consistent, and it was good. The original version of cout and cin lived in iostream.h. When the language was standardized by the ANSI committee, they decided to move all of the functions in the runtime library into the std namespace (which is generally a good idea). However, this presented a problem: if they moved all the functions into the std namespace, none of the old programs would work any more!

To try to get around this issue and provide backwards compatibility for older programs, a new set of header files was introduced that use the same names but lack the .h extension. These new header files have all their functionality inside the std namespace. This way, older programs that include #include <iostream.h> do not need to be rewritten, and newer programs can #include <iostream>.

When you include a header file from the standard library, make sure you use the non .h version if it exists. Otherwise you will be using a deprecated version of the header that is no longer supported.

In addition, many of the libraries inherited from C that were still useful in C++ were given a c prefix (e.g. stdlib.h became cstdlib). The functionality from these libraries was also moved into the std namespace to help avoid naming collisions.

However, when you write your own header files, you should give them all a .h extension, since you will not be putting your code in the std namespace.

Rule: use the non .h version of a library if it exists, and access the functionality through the std namespace. If the non .h version does not exist, or you are creating your own headers, use the .h version

Including header files from other directories

Another common question involves how to include header files from other directories.

One (bad) way to do this is to include a relative path to the header file you want to include as part of the #include line. For example:

The downside of this approach is that it requires you to reflect your directory structure in your code. If you ever update your directory structure, your code won’t work any more.

A better method is to tell your compiler or IDE that you have a bunch of header files in some other location, so that it will look there when it can’t find them in the current directory. This can generally be done by setting an “include path” or “search directory” in your IDE project settings.

In Visual Studio, you can right click on your project in the Solution Explorer, and choose “Properties”, then the “VC++ Directories” tab. From here, you will see a line called “Include Directories”. Add your include directories there.

In Code::Blocks, go to the Project menu and select “Build Options”, then the “Search directories” tab. Add your include directories there.

Using g++, you can use the -I option to specify an alternate include directory.

The nice thing about this approach is that if you ever change your directory structure, you only have to change a single compiler or IDE setting instead of every code file.

Can I put function or variable definitions in a header file?

You shouldn’t, as it may cause linker errors. We’ll explain why in the upcoming lesson on header guards.

Declarations are okay.

Header file best practices

Here are a few best practices for creating your own header files.

  • Always include header guards.
  • Do not define variables in header files unless they are constants. Header files should generally only be used for declarations.
  • Do not define functions in header files.
  • Each header file should have a specific job, and be as independent as possible. For example, you might put all your declarations related to functionality A in A.h and all your declarations related to functionality B in B.h. That way if you only care about A later, you can just include A.h and not get any of the stuff related to B.
  • Give your header files the same name as the source files they’re associated with (e.g. grades.h goes with grades.cpp).
  • Try to minimize the number of other header files you #include in your header files. Only #include what is necessary.
  • Do not #include .cpp files.
1.10 -- A first look at the preprocessor
1.8a -- Naming conflicts and the std namespace

328 comments to 1.9 — Header files

  • Sivasankar

    Hi Alex,

    Thanks a lot for your awesome tutorials.

    In "Can I put function definitions in a header file?" section, you said that there will not be any issue if function definitions are put in header file. Won’t it cause linker errors if the same header file is included in multiple files (i.e. the same function is defined in multiple files)?

    • Alex

      Good point. I’ve updated the section to make it more clear that this will probably cause linker errors. I talk about why this happens in the upcoming chapter on header guards.

  • UV

    While i am compiling my add.cpp code i got the following message

    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 12
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 21
    /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
    /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start’:
    (.text+0x20): undefined reference to `main’
    collect2: error: ld returned 1 exit status

    • Alex

      This is the key error: /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start’: (.text+0x20): undefined reference to `main’

      Your program doesn’t have a main() function. You need to create one.

  • AMG

    Many, many thanks for your time and efforts to explain C++ to the rest of the world. Amazing! In this chapter (1.9) identical names for add.h, add.cpp and function ‘add()’ may create a wrong pattern in naming files. For example, Kiril followed "add" naming style and used ‘calc’ to replace ‘add’ from your example. In other words, add.h -> myarithmetic.h, add.cpp-> myarithmetic.cpp. I think it would be better if file names would tell about content. Sorry, if my comment caused wasting your time.

  • Anshul

    Why we don’t need to #include<iostream> in each source code file? add.cpp and main.cpp are compiled independently; to use cout functionality in add.cpp shouldn’t we #include<iostream> here too?

    • Alex

      Yes, you should include iostream in any file that uses the functionality that iostream defines.

      In the example above, add.cpp does not use iostream, so including it is not necessary. If you decided to use std::cout in add.cpp, you’d need to include the iostream header in add.cpp.

  • mrlorin

    I’m really enjoying these tutorials, especially the Douglas Adams tribute?

  • jamesL

    Hey, your ifndef statement in the header guard is not indented properly, you should always indent your if statements, remember? ;D

    So anyway, I was wondering if there were any simple audio libraries available that you can use in these types of console applications to make chiptune like music. No MIDI libs please, and i’m wanting to create the music myself from written source files so things like libmodplug or game music emu are not what i’m looking for either (though I probably will try those out at some point).Really I just want it to handle the basic stuff like creating the sound buffer, generating the waveform, placing the waveform in said buffer, etc.

    • Alex

      if statements and ifdef/ifndef are two different things.

      For sound stuff, you might check out Simple DirectMedia Layer (SDL).

      • jamesL

        Well I know they are different, one is preprocessor and one is actual program logic 🙂 But I would still write them both the same way anyway.

        Also yeah i have heard good things about SDL. But does it work in the console or does it require a win32 application, because I’m not exactly good enough to make those yet 🙁

        • Alex

          I think SDL will work with console apps as long as you’re not using any of the GUI stuff. But I’m not sure -- I’ve used SDL a few times but only as a Windows app. My knowledge of Windows apps is super-minimal, but it wasn’t difficult to get set up. There are tutorials for such things. 🙂

  • Ashish


    #ifndef add
    #define add

    int add(int x, int y);



    C:\CBProjects\helloworld\add.h:7:9: error: expected unqualified-id before ‘int’
    int add(int x, int y); // function prototype for add.h -- don’t forget the semicolon!
    C:\CBProjects\helloworld\add.h:7:9: error: expected ‘)’ before ‘int’
    Process terminated with status 1 (0 minute(s), 0 second(s))
    2 error(s), 0 warning(s) (0 minute(s), 0 second(s))

    • Alex

      You’re getting a naming conflict between your header guard name and your function name. This is why we typically would use ADD_H for the header guard name, because it won’t conflict with anything else.

      • ASHISH

        ITS NOT WORKING still!!

        // This is start of the header guard.  ADD_H can be any unique name.  By convention, we use the name of the header
        #ifndef ADD_H
        #define add

        // This is the content of the .h file, which is where the declarations go
        int add(int a, int b); // function prototype for add.h -- don’t forget the semicolon!

        // This is the end of the header guard

  • this is man.cpp, for my header file

    and I pressed on new, then chose the file option and header file to make a header file and I named it man.h

    and then I made a new project called lo and in the main.cpp I added this

    but when I compile it says "fatal error :man.h: No such file or directory."
    I tried using <man.h> instead of "man.h" and I got the same result. Can anyone help me solve this please?

  • Abheet


    I have a question regarding how header files and cpp files linkup.
    Here it is:

    How does main.cpp search for the add.cpp? I mean, main.cpp knows about add.h, thus main.cpp is sure that add() function exists.
    However how does it find it? Like what is the procedure main.cpp is supposed to follow to look for the add.cpp file?

    Is this how it works? :

    main.cpp: "Alright, add.h told me add() function exists, fine. Now I will just look around and hope that cpp file containing the
    exact code is named the same as add.h (i.e add.cpp)"

    Or is it like this :

    main.cpp: "Alright, add.h told me add() function exists, fine. Now as the only other cpp file linked to me is add.cpp, so that
    must have the code I need!"

    [ What if there are 2 cpp files linked to the main.cpp file? ]

    (A flow diagram would certainly help me! Thanks, again!)

    • Alex

      main.cpp knows nothing about add.cpp. Main.cpp and add.cpp get compiled independently (unaware of each other). It’s only at the linker stage that the results of each get combined.

      So it’s more like: “compiler: add.h told me add() function exists. I have no idea where, but I’ll trust that that is true. linker: I’m going to connect up this call to add() in main.cpp with the definition of add() in add.cpp.”

      • Abheet

        Okay that cleared it up a bit!

        So basically the linker hunts for the cpp file containing the definition of add() function and links the found file (add.cpp) to main.cpp right?

        Thanks a lot for quick response!

        • Alex

          Yup, the linker takes all of the object files that the compiler created, links them together, and connects any cross-file references.

  • Alex

    Hi Alex,

    Is it correct to assume that once a header file has so many functions declared inside it, you have to create namespaces for efficiency?

    Many thanks

    • Alex

      No. Namespaces do not add any efficiency. They exist solely for organizational purposes, to help prevent naming collisions.

      The larger your program is, the more benefit you gain from using namespaces. The Google C++ style guide recommends putting all your code in namespaces. This makes sense for a company that does a lot of code sharing. If you’re creating your own programs for your own use, namespacing your own code probably isn’t necessary.

  • sam

    for people who are using visual studio 2017:
    you can access your project properties by clicking on the "project" tab of top of the screen >> "project name" properties -in my case i see learning2 properties-

    because right clicking on your project in the solution explorer won’t get you to the project properties.

  • B1

    hi Alex
    i hope i get answers for my questions ^_^

    1. where is the source code for C++ itself ?!!
    i have search everywhere but no luck

    2. in what language C++ was writing ?!!

    3. can we remove ALL the C libraries & headers from C++ ?
    i want C++ to be 100% pure, can we do that ?!!
    is there someone tried that or something, if so please give me the URL

    thank you

    • Alex

      1) It’s not. C++ is distributed as a set of precompiled libraries and header files. You can look at the code in the header files, but not in the precompiled libraries.
      2) Originally, assembly. These days, I’m not sure. It’s possible the C++ compiler is written using a previous version of the C++ compiler.
      3) No. Those provide all of the C++ runtimes and standard library.

  • Erik

    Maybe I missed it, but how do you compile the example? "g++ main.cpp" doesn’t work, a flag is needed but which one?

  • saurav

    so i was compiling the program without using the header file,just by using function prototype and i got this

    here is my add.cpp

    here is my main.cpp

    and i get this error

    in function ‘main’
    undefined reference to ‘ad(int, int)
    what seems to be the problem??i have both the files in same project

    • Alex

      Could be one of two things:
      1) Make sure that function add is spelled correctly (your error message says “ad” rather than “add”, but this could just be a typo)
      2) Make sure add.cpp is added to your C++ project so that it is compiled in. When you compile your program you should see the compiler compiling it.

  • I’m very pleased to uncover this site. I want to to thank you for your time for
    this wonderful read!! I definitely enjoyed every bit of it
    and I have you book marked to see new things on your web

  • Kiril

    Here is the little Mathematical program i made just to test what have i learned by now.
    What do you think Alex? About the code.




    • Alex

      Function calc() definitely needs a comment indicating what it does. You should also define your variables closer to where you use them rather than at the top of functions.

  • andresmetalowl

    Alex help!
    I could not include it can you explain me why?

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

    void add(int x, int y)
        std::cout << x + y << std::endl;

    int multiply(int x, int y)
        return x * y;

    int main(int x, int y)
        std::cout << awesome() << std::endl;
        std::cin >> x;
        std::cin >> y;
        add(x, y);
        std::cout << multiply(x, y) << std::endl;
        return 0;


    #include "stdafx.h"
    #include "iostream"

    int awesome()
        std::cout << "hello" << std::endl;
        std::cout << "Put 2 numbers please" << std::endl;
        return 0;

    #ifndef AWESOME_H
    #define AWESOME_H

    int awesome();


    • Alex

      If you mean that you awesome.h is failing to be included, the most likely cause is that awesome.h was saved to some directly that your compiler/IDE isn’t set up to look for header files in. Make sure you’ve saved it to the proper directory, or change your include directories to include the directory where awesome.h is living.

  • My dear c++ Teacher, (I mean that),
    Please let me say that in graph (diagram) file add.cpp is compiled in parallel to main.cpp, but as you state in a reply to me, compiler compiles files (and lines) sequentially. Accordingly, given that add.cpp was created AFTER main.cpp should be compiled AFTER it. That’s my understanding so far.
    With regards and friendship.

    • Alex

      It is up to the IDE to determine what order to compile files in. Just because add.cpp was created after main.cpp does not mean it will be compiled after main.cpp.

  • manikanth

    what is the difference between <iostream> and namespace std for cout, how they explain the compiler?

    • Alex

      Iostream is a header that contains all the definitions that you need to use input and output routines. Without the iostream header, the compiler doesn’t know what std::cout and std::endl are, or how operator<< should work. Including this header allows the compiler to understand what these things are.

      Within the iostream header, all of these definitions are defined inside the std namespace. So to actually access them, you need to use the std:: prefix to access them.

  • I am getting the error "error: ld returned 1 exit status" with the following program:




    I am using Code:Blocks and all the files are associated with the project and set to be Built/linked/and set to debug and release. How can I fix this?

    • Alex

      Are you getting any other error messages?

      • Never mind, I seem to have fixed the issue. For other people reading this comments section, this is my updated main.cpp:

        Also, it’s great that you’re still following all these comment sections and helping us! And your tutorials are very well written.

  • ritesh tyagi

    hi alex, my question is if the code in the header file is already included in the source file then why we compile the header file?

    • Alex

      I’m not sure I understand the question. Header files are not compiled directly. Instead, they’re #included into code files, which copies the contents of the header into the code file, and then the code file is compiled.

      • ritesh tyagi

        thanks a lot Alex for quick reply ….as i am using codeblock….i add the .h file in my project and my code  could not run then i saw  in my .h file properties  that compile option is not checked , i checked then my code ran ok . so this whole scenario led me arise this question , by the way u got it right .and i got the answer as well..the question was do  we need to compile the header files separately???

        • Alex

          No, you should not be compiling your header files separately. They should only be compiled indirectly by being #included into .cpp files, which get compiled.

  • Rafael

    Can any one please help me? Every time that I try to compile my project, the following error
    "1>---- Build started: Project: Maths, Configuration: Debug Win32 ----
    1>  Maths.cpp
    1>c:usersleafadesktopprogrammingmathsmathsmaths.cpp(1): fatal error C1083: Cannot open precompiled header file: ‘DebugMaths.pch’: No such file or directory
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped =========="

    The code I created are the following:

    [#ifndef MathFunctions_H
    #define MathFunctions_H

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

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

    int devide(int x, int y)
        return x / y;

    int multiply(int x, int y)
        return x * y;



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

    using namespace std;

    int main()
        cout << add(3, 4) << endl;
        return 0;

  • Sarah

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

    //comments only
    int main()
        std::cout << "Hello World!" << std::endl;

        int x,y;
        //int y;
          x = 12;
           y = 7;
        std::cout << y << std::endl;
        int z;
        std::cout << "Please pick a number" << std::endl;
        std::cin >> z;
        std:: cout << "You entered " << z << std::endl;

        std::cout << "The sum of 3, 4 and 100 is: " << add1(3, 4, 100) << std::endl;
        return 0;

  • Sarah

    Hi, I had created 2 projects one called Function1_4.cpp and one HelloWorld.cpp. In the Function4_1 I have Add1.cpp and Add1.h , test.cpp. In the header Add1.h I have both Add1 and Test initiated. I had add #include "add1.h" in Function4_1.cpp up to this point I have no problem to call both functions (Add1 and test) that was initiated in Add1.h. My problem is I want to call #include "add1.h" in other project HelloWorld  by just adding the path of Add1.h into IDE project settings.

    Error    LNK2019    unresolved external symbol "int __cdecl add1(int,int,int)" (?add1@@YAHHHH@Z) referenced in function _main    HelloWorld    C:\Users\fatima\Documents\HelloWorld\HelloWorld\HelloWorld.obj    1

    • Alex

      If you’re going to use function add() from HelloWorld, you need to #include add1.h, AND make sure add1.cpp is added to your HelloWorld project so that the definition for function add() is compiled into the project.

  • Matthew

    Where it says "[h]eader guards prevent a given header file from being #included more than once in the same file", I am not really sure if I am understanding what this means. Does this mean the header guard prevents a file from using "#include add.h" more than once in the same file (main.cpp in this example)? It doesn’t make sense to me why one would write the same preprocessor directive more than once in the same file.

    Also, thanks very much for these lessons Alex. I am finding them very helpful for deepening my understanding with the c++ programming language. I hope I can make it to the end eventually.

    • Igna

      You can inlcude more than once header files like this supose you have this files:






      As you can see in the main.cpp you include add.h and double.h and also in double.cpp you include add.h again so if I am not wrong the header guards prevents that a given header is included more than once so there is no a name collision there… I hope that that was the answer you are looking for and sorry about my English but I am Argentinian so I speak Spanish

    • Alex

      > Does this mean the header guard prevents a file from using “#include add.h” more than once in the same file (main.cpp in this example)?

      Close, but no. Header guards prevent the _content_ of a header file from being included more than once in the same file (main.cpp in this example).

      It would be silly to directly #include add.h more than once. But what if you included math.h, and math.h included add.h? Then the contents of add.h would be included twice (once directly, and once through math.h). Header guards prevent this from happening.

  • anony

    not a question, but a remark

    Regarding not putting the relative path of header files, but rather having the compiler know all the paths where to search.

    This is fine for small and medium projects, but in multi-programmer professional projects having hundreds or thousands of files, this approach can become a hindrance since the path is informative. When a programmer is looking at #include declarations it becomes very helpful to know which directory they come from because this not only helps locate the header more easily, but also informs how the .cpp file depends on other parts of the project since the directory structure reflects the project’s organization.

    If the directory structure needs to change (beyond simply renaming directories), then there are much bigger issues with the project than having to manually go through and fix the #includes, since this probably means that there were serious problems in the project’s design, so there are much bigger changes needed beyond fixing #includes which is rather easy.

  • My dear c++ Teacher,
    Please let me as ask your experienced suggestion on that: I created two Projects with Dev-C++ 5.11 but file main.cpp should be common! so in Project1 I given name for main file: main1.cpp. It works fine! Do you consider this naming okay?
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me express my thanks for reverting article "the" to "a" before "previous lesson". Also let me ask: by saying, "Header guards prevent a given header file from being #included more than once from the same file" do you mean: "in the same file"?
    Also ask: can I think header files as directories in the sense of tree structure?
    With regards and friendship.

  • My dear Teacher,
    Please let me say that under "Writing your own header files" you state: "Now let’s go back to the example we were discussing in the previous lesson. When we left off, we had two files, add.cpp and main.cpp, that looked like this:"
    Actually we were discussing this example in lesson "1.8 — Programs with multiple files". Previous is "1.8a — Naming conflicts and the std namespace".
    With regards and friendship.

  • Matt

    Typo under "Writing your own header files":
    "We’d used a forward declaration so that the compiler would know what add was when compiling main.cpp."

    I think "we’d" should be "we".

  • Eleanor

    I’m a little confused about the how some of the predefined headers work

    I’m using Xcode, and when I create a header file it automatically places #include <stdio.h> at the top of the add.hpp file.
    Specifically, it spits this out:

    I can use it fine when I type my declaration in, it all works great and spits out the program as I’d expect.  

    My understanding is that <stdio.h> works a lot like <iostream> in that it declares certain functions like printf etc. which are useful for the same reason we declare functions like cout, cin, etc.  When I delete "#include <stdio.h>" the program still runs fine, presumably because I’m not using any of the functions it declares.

    I just don’t understand why it appears within the header file and not the .cpp file?  Is there any benefit to placing it within the header file?

    Aren’t header programs only meant to be used to declare a bunch of functions?  Why would you ever need to include cout, cin, printf, or anything else in the header?

    Thank you so much for these tutorials!

    • Alex

      I honestly don’t know why xcode would automatically #include stdio.h in your header files.

      It would make sense for your header to #include stdio.h if your header used anything defined in stdio.h -- but if that’s not the case (and it sounds like it’s not), then you should remove it.

  • yash

    ive run this programme but have output that graphic.header not found so what to do plz help me out in this urgently rply

    // lots of code removed

  • kanishk

    where am i going wrong?
    the error shows- 1d returned 1 exit status.

  • Marshall H Crenshaw

    I am using Visual Studio Community 2015. I find I am using functions to input and check integers & characters, keep the console window open, asking yes or no to continue, etc. in a lot of projects. I want to put these common functions in a separate folder such as C:\\MHC-CPP, and then add them to my projects when I need them. Build up a little library of common functions I’m using in this tutorial. So this lesson is the first time I’ve understood how to do this using header files and adding files to my project.

    It took me some time to figure out what to do, so I thought I would post it here in case anyone else needs help.

    First to add the .cpp files to my project:
    On the right hand side of the Microsoft Visual Studio main window is the Solution Explorer frame (unless you moved it somewhere else). Right click on the Source Files folder and choose Add > Existing Item. A file selection window will open. Navigate to where your .cpp file is stored (mine are in C:\MHC-CPP) and select the .cpp file you want to add to your project. Click on Add and your file will be added to your project.

    Next to add the directory for the .h files:
    You want to #include the header file .h (which should contain the function definitions for the .cpp file you added above) into your main project (project.cpp). However you don’t want to have to copy the .h files into your project’s directory every time you have a new project, as this would defeat the purpose of having a central place to put your own code. So you have to tell the project where the directory is that contains your .h files.
    In the Solution Explorer frame, right click on the project name and choose Properties. The project Property Pages opens. I use Configurations: All Configurations. In the frame to the left select Configuration Properties:C/C++:General. In the frame on the right the top line should be Additional Include Directories. Click on the box to the right and a small down arrow should appear at the end of the line. Click on the arrow and choose <Edit>… A pop-up window opens called Additional Include Directories. Click on the *Folder icon (New Line). Click on the … at the end of the line and a Select Directory window will open. Navigate to the directory you have your .h files in (in my case C:\MHC-CPP) and choose Select Folder. Click on OK.
    Now when you use #include it will look in the other directory too and find your personal .h files.

    Precompiled headers and stdafx.h
    I’ve also read that I shouldn’t disable the "using precompiled headers" option, since later on with large projects this will be helpful. The problem is with the darn #include "stdafx.h" that VS 2015 requires as the first line in every .cpp source file. Every .cpp file has to have this as the first line. The problem is when the .cpp file is in a different directory than the project, the compiler looks for the "file" in the same directory as the .cpp file. This generates a compiler error because it can’t locate the file (a squiggly red line appears under the file name). It doesn’t seem to know to look in the project directory. So you have to tell the compiler where to look for that file.
    So repeat the above for the Additional Include Directories, except choose the first directory it opens to, which should be your project directory. Mine is at c:\Users\Marshall\Documents\Visual Studio 2015\Projects\CPP\projectname\projectname. Add this to the additional include directories. Now it works!

    Unfortunately you have to repeat the above process for every new project. But if you change the location of your "libraries" you only have to change it in the Property for the project and not in the individual files.

    Hope this detailed walk-through saves someone some time.

  • John

    Thanks for an excellent site.

    Would you say that the code shown below is correct? Note that there are two inclusions of <iostream>, once in main.cpp and once in functions.cpp.

    Compiled with: g++ -o test main.cpp functions.cpp

    • Alex

      Yes, outside of the fact that you’ve used “using namespace std;” in the global scope. 🙂

      It’s not only fine to include iostream from both main.cpp and functions.cpp, it’s also necessary.

  • Tudor

    Hi Alex!
    Thank you for the excellent turorials =)

    I’ve followed the section on header files to the letter.
    Here’s my code:

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

    int main()

        using namespace std;
        cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
        return 0;

    And here’s my error message:

    --------- Build file: "no target" in "no project" (compiler: unknown)----------

    mingw32-g++.exe   -c "C:\Users\Draeforthe\Desktop\My Project\include file test.cpp" -o "C:\Users\Draeforthe\Desktop\My Project\include file test.o"
    mingw32-g++.exe  -o "C:\Users\Draeforthe\Desktop\My Project\include file test.exe" "C:\Users\Draeforthe\Desktop\My Project\include file test.o"  
    C:\Users\Draeforthe\Desktop\My Project\include file test.o:include file test.cpp:(.text+0x27): undefined reference to `add(int, int)’
    collect2.exe: error: ld returned 1 exit status
    Process terminated with status 1 (0 minute(s), 4 second(s))
    2 error(s), 0 warning(s) (0 minute(s), 4 second(s))

    I’m flummoxed. Any help I can get would be appreciated.

    • Alex

      So it looks like your compiler is compiling test.cpp, and then the linker is telling you that it can’t find a definition for function add(). Did you define add() anywhere? If you didn’t, that’s your problem. If you did, then whatever file you defined it in (add.cpp maybe?) isn’t getting compiled into your project.

  • Theo

    Greetings Alex,

    The tutorial is awesome, the best I have read on a programming language.
    I think I followed the instructions correctly but I get this error;
    Fatal error LNK1120: 1 unresolved externals.

    This is my code and where files are located:

    add.h located below  Header Files:

    #ifndef ADD_H
    #define ADD_H

    int add(int x, int y);


    main.cpp under Source Files:

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

    int main()
        using namespace std;
        cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
        return 0;

    add.cpp under Source Files:

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

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

    And two more things, what is #pragma once that Visual studio 2015 writes on Header Files?
    How come we name the header add.h and we write in in capital in #define ADD_H
    Thank you

    • Alex

      I don’t see anything wrong with your code or names, so did you remember to add add.cpp to your project, so that it gets compiled? When doing a full recompile, you should see add.cpp show up in the list of files your compiler is compiling.

      I talk about what #pragma is in either the next lesson or the lesson beyond that one.

      It’s common convention to make your #define values all caps.

      • Theo

        The add.cpp is located under Source Files along with main.cpp. Is this what you mean? Or am I supposed to add it elsewhere as well? I was under the impression that whatever is under Source Files is part of the project. Or do I have it completely wrong?

        • Alex

          If it’s in your project’s source files, it should get compiled. Do you see it compiling when you compile your program?

          If you move function add() from add.cpp to main.cpp, does it compile? If so, then something is going wrong with the compiling and linking of add.cpp.

          • Theo

            Yes it was including add.cpp when i tried to compile it. It gives me the same issue even when I removed add.h and add.cpp and put everything inn main.cpp. Anyway thanks for the help Alex, really appreciate it, I will have a developer friend have a look at it later in the week. It’s will be easier since he will be looking at it from my screen 🙂

  • Rahul

    This one I wrote as main.cpp

    #include "stdafx.h"
    #include "add.h"

    int main()
        std::cout << "The sum of 4 and 4 :"<<
        add(4, 4) << std::endl;
        std::cout << add_h ;
        return 0;

    and add.h and add.cpp is same as you defined, but after compiling I got this error
    error C2059: syntax error: ‘;’
    What is the meaning of this?

    • Alex

      I’m not sure what line you’re getting the error on. The compiler is telling you that it found a ; character where it was expecting something else. I’m guessing that it’s complaining about this line:

      Because this makes no sense. What were you expecting this line to do?

  • Rahul

    Why did you write #define ADD_H after #ifndef ADD_H in add.h?
    What is the use of #define over there?
    And thanks these lessons are great!!

  • Ivar

    What is the reason for this best practice:

    "Try to minimize the number of other header files you #include in your header files. Only #include what is necessary."

    Assuming the header files only include declarations, #including them should not have an effect on memory usage or compile time, right? (Of course it makes no sense to #include stuff you don’t use, I’m just curious if there is a specific reason since it was mentioned explicitly.)

    Thanks for an amazing tutorial!

    • Alex

      There are quite a few reasons for this:
      * It could slow down compilation. All those declarations need to get parsed and stored while the compile is compiling.
      * You could pollute the global namespace, making it a lot more likely you’ll run into naming collision issues (not as much of a problem with the standard library since it’s all in the std namespace).
      * It adds a lot of unnecessary dependencies to your code.
      * Including extra header files hides the real dependencies.

      Or, to answer the question philosophically, if they thought this was a good idea, why wouldn’t they make it easy to do so? 🙂

  • Nishtha

    What is the diff between adding a namespace and header file? Also, you mentioned that when we write include iostream.h, cout function is only defind in this header file and actual definition is somewhere else, but when we made our own header file, y we have added definition also? Y not we have placed it somewhere else.

    • Raquib

      1- If I understand correctly what you are asking is , "if I am already including <iostream> why the hell do I need to add ‘std::identifier’ (recommended way) or ‘using namespace std’ " ? you think so maybe becoz you expect when you #include<iostream> all of these(cin, cout, etc.) identifier to be included. But that is not how it is, in C++ all the identifier are grouped together under the namespace std. You can check the iostream header file where you have installed C++.

      Looks something like-

      namespace std {
        extern istream cin;        /// Linked to standard input
        extern ostream cout;        /// Linked to standard output
        extern ostream cerr;        /// Linked to standard error (unbuffered)
        extern ostream clog;        /// Linked to standard error (buffered);

      So to access cin, cout etc. you need to tell the compiler where these are ( its Scope). That’s what using namespace std, does.

      Also remember, iostream is not the only header file that puts stuff in the namespace std. There are other headerfiles which does as well.

      Apart from that, adding namespace avoids naming conflicts of identifiers, coz you limit the scope of identifier say cin, within the namespace std.

      2. Yes, cout is actually only declared in the iostream headerfile under namespace std. The actual definition is in the runtime support library.
      When you are also making your own headerfile, it should only contain declarations. The actual definition should be in a separate cpp source file. Remember, this is just a recommendation, since it is a good practice.
      Even this tutorial does that, I think you missed it. Here you go ----

      // This is start of the header guard.  ADD_H can be any unique name.  By convention, we use the name of the header file.
      #ifndef ADD_H
      #define ADD_H

      // This is the content of the .h file, which is where the declarations go
      int add(int x, int y); // function prototype for add.h -- don’t forget the semicolon!

      // This is the end of the header guard
      In order to use this header file in main.cpp, we have to include it.

      main.cpp that includes add.h:

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

      int main()
          using namespace std;
          cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
          return 0;

      add.cpp stays the same:

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

    • Alex

      > What is the diff between adding a namespace and header file?

      These two things are dissimilar enough I’m not sure where you’re getting confused. Can you be more specific about where your confusion is?

      > Also, you mentioned that when we write include iostream.h, cout function is only defind in this header file and actual definition is somewhere else, but when we made our own header file, y we have added definition also? Y not we have placed it somewhere else.

      The definition for std::cout is part of the standard library, which gets linked in as part of the linking phase. For the code you write, you have to supply the definition so that the compiler can compile it.

  • Jim

    Alex & Code::blocks users: Here are a couple of points that I’ve discovered using CB. I’m using CB 16.01.

    1. If you want to enter a header file into codeblocks.

    You need to use File Menu->Empty File, answer yes to add it to the existing project, and save it in the windows dialog box with the file named add.h.

    2. If you have worked on the add function program and added a add.h header file to your program in the project.

    If it  won’t compile make sure you have the released version turned on and not the debug version.

  • Tristan Gybels

    I get it right now 😉 I just read your explanations over and over again.
    Sometimes it’s just hard to understand for some foreign people.

  • Tristan Gybels

    You are a good teacher and you do explain everything well, but this is a hard lesson to me :/
    Possibly because I don’t speak English as a main language.
    More examples would be lovely to see in this chapter.
    Visual parts are the most effective to learn for me.

  • Chris

    Here is my code, thanks for the tutorial
    its very informative and gets straight to
    the point. Its easier to understand than
    my Book on C++.

  • i have 2 projects:  add.cpp and main.cpp

    i added the codes to both

    then i created add.h

    and added the codes in that too

    then i created a new directory and added :
    main.cpp , add.cpp and add.h into that folder(all files of the projects)
    then started main.cpp

    #include "add.cpp"

    into the code and that ran correctly.
    (i didn’t add anything to active projects and everything is in one directory)
    is that fine?
    will it work when my program gets bigger?

    • Alex

      > will it work when my program gets bigger?

      No. You should not #include other .cpp files. You will run into problems later.

      You should create a single project and add files add.cpp and main.cpp to it.

  • Ryan

    Great tutorial!!

    I have the following error:

        C1083 cannot open include file:’add.h’ no such file or directory

  • Nathan

    The only website I would consider turning off ad block for. Thanks for all the hard work you put into this site!

  • Nyap

    The C++ Standard Library contains all the declerations
    The Standard Runtime Library contains all the definitions

    • Sihoo

      February 18, 2016 at 5:25 pm · Reply
      a) No, when people talk about the “iostream library” they’re really talking about the iostream functionality inside the C++ standard library.
      b) The runtime support library is the same thing as the C++ standard library. I’ll update the language in lesson 0.4.

      Above is the author wrote an answer to another question similar to yours.

      So basically, C++ Standard Library is used interchangeably with Standard Runtime Library or Runtime Support Library. When we say C++ standard library, it basically refers to both headers files(declarations) AND corresponding definitions for these declarations, which are already precompiled as binary codes.

      Alex explains in detail about this on Section A.1. Below is the link.

  • Carl

    In the add.h file I had the Compile file & Link file boxes checked under Properties/Build and when building the project it threw up the errors mentioned. Removing the checks cured it.

    Hope that clarifies things.

    Once again, a huge thank you for the time and effort on your part for producing such a brilliant site.


  • Carl


    Absolutely brilliant tutorial - and all for free!!

    Using Code::Blocks 16.01 and had difficulty with 1-9 Header files. Kept getting "ld returned 1 exit status" in the build messages and in the build log references to "add.h.gch file not found". Did a bit of Googling and found it was due to the Compile/Link boxes being checked on the Properties/Build tab.

    Reading down the comments it seems one or two folk have experienced this.  Could you mention it in the tutorial in the bit that talks about compiler error please?

    Or have I missed something? (likely!!)

  • person

    you said in multi file projects, we can add files.
    what would happen if we #include a .cpp file.

    would that do the same thing as adding the file to a project.
    if not, what would it do?

    • Alex

      No, it’s not the same thing as adding a file to the project. When you add a file to the project, it gets compiled as a separate unit. If you #include a .cpp file in another .cpp file, the contents of the included file become part of the includer, and they are treated as one file. I’m not aware of any good reasons to #include .cpp files.

  • Janaka

    You are the Best Teacher I seen in the internet university. Thank you very much.

  • Danny

    do we need to add #include "stdafx.h" inside *.h files or any non .c/.cpp ?

    here my code




    i did try to omit #include"stdafx.h" in doubleNumber.h without any noticeable problem, am i doing it right? please explain

    • Alex

      #include “stdafx.h” is only needed when ALL of the following are true:
      * If you are in a .cpp file
      * If you are using Visual Studio
      * If precompiled headers are turned on (they are by default)

  • PurpleKitty

    How can I get Dev C++ to use the auto <> {} "" () instead of me manually have to put both

  • SUMOman

    1st thing that comes to my mind is why iostream is not iostream.cpp(forward declared)…It will be much more efficient than iostream…Some people say that when a program is executed…the exe file will be dependent on the other cpp file during execution in case of forward declarations,which is nonsense because exe file is a machine level language and cpp is a high level language…And i actually copied the exe file   formed from the project to the desktop,deleted the project file and ran the exe file to see if there were any dependencies….Turned out there were no dependencies…Luckily i restored the deleted project from the bin…lol..I dont understand the use of the header file

    • Alex

      > 1st thing that comes to my mind is why iostream is not iostream.cpp(forward declared)…It will be much more efficient than iostream…

      I don’t understand what you’re suggesting.

      “#include ” imports the declarations necessary for your code to use the functionality of iostream (the classes and functions that make up iostream). iostream.cpp is not made available to you -- instead, all you get is the precompiled standard runtime library (which the linker links in).

      • Sihoo

        iostream.cpp is not made available to you -- instead, all you get is the precompiled standard runtime library (which the linker links in).

        Thank you for this explanation. I was spending quite a long time trying to find the cpp files for the library functions. Thought I will be able to find them just like header files, but I guess not since they are not made available to a user.

  • Nathan

    Hi Alex, loving this site!
    I’m still struggling to understand why you would want to use headers instead of forward declarations. It seems to me that creating a new header file AS WELL AS the cpp file just creates a lot of unnecessary work.

    For example, I did your adding example (but with an added function that gets two inputs from the user and adds them), and used different cpp files for each function (so main.cpp, add.cpp and getNumber.cpp), using forward declarations. I then went and redid that program with header files. Both programs do exactly the same thing, but the header file one uses an extra 3 files, each containing an extra 4 lines of code. It seems to me that in the long run this would really get complicated!

    Thanks in advance for your answer, and thanks for the work you put into this site!

    • Alex

      In reality, you’d almost never make one file per function. As you note, this would get really complicated.

      Generally a single code file will represent a collection of related functions, and the header file contains all of the forward declarations for the code in that file. That way, anyone who wants to use the code in that file can #include the header file (one line of code once set up) rather than having to individually copy the function prototype for each function used.

      Furthermore, if you ever update a function’s prototype, the change only needs to be reflected in the code file and the header. That change will be propagated to all #includers. If you manually copy/paste prototypes into your code file, you’d have to update each one individually.

      Also note that so far, we’ve just talked about functions, and functions are relatively straightforward. Later on, we’ll discuss how to create your own new types of data. Those can get really complicated, and you definitely will want to use headers to propagate the forward declarations for those instead of copying the type declarations into multiple files.

      In short, header files don’t really save much work if you’re only using the content of a file in one other file. However, beyond that, they do improve organizational structure, and help prevent redundancy when a function (or other type of object) needs to be included in multiple places.

      • Nathan

        Thanks for the quick reply, I don’t know why I didn’t consider files containing multiple functions. It makes perfect sense now 🙂
        Thanks again for your continued work on this site!

  • moses

    Thanks Alex, runs like a top now.

  • moses

    first thank you for the great tutorial. 🙂
    second here’s my issue. I have compiled all source code according to the tutorial. I know that add.cpp & main.cpp are correctly defined and that add.cpp is included (correctly) in the main solution because main does execute properly when the function prototype (for add.cpp) is used in main. When I execute (so far I’ve always done so using "start without debugging") main without the function prototype but with [#include "add.h"] I get the following errors :
       |Code |Description        |Project |File     |Line
    abc       cannot open         main     main.cpp  6
              source file
       c1083  cannot open         main     main.cpp  6
              include file:
              ‘add.h’: No such
              file or directory
    abc       identifier "add" is main     main.cpp  13
    Here’s my code (I’m not sure if I’m using the [] brackets correctly for syntax highlighting but here goes).
    [//main.cpp : Defines the entry point for the console application.//

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

    int main()
    using namespace std;
    cout << "the sum of 3 and 4 is :" << add(3, 4) << endl;
    return 0;

    [#include "stdafx.h"
    #ifndef ADD_H
    #define ADD_H

    int add(int x, int y);


    [// add.cpp : Defines the entry point for the console application.//
    #include "stdafx.h"
    #include <iostream>

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

    I’m using visual studios 2015. the only thing I don’t understand is why main isn’t able to open add.h . I also have this included in the main solution as add.h . It shows it as an add.h.cpp file just like it shows the other programs as main.cpp & add.cpp files all under source files in the main solution. It’s worth noting (maybe :)) that I first compiled add.cpp then main.cpp then added add.cpp to main.cpp while main was open by right clicking on "Source Files" then "Add-Existing Item". I then (after successfully compiling and running main.cpp w/the [int add(int x, int y);] function prototype,right clicked again on "Source Files" then selected, "Add-New Item", then wrote the add.h as a cpp file. After seeing that the add.h file had been successfully added in the solution explorer window, I ran the main.cpp as I showed above (without the function prototype and with the [#include "add.h"]). As I said, it might be worth noting that when I went I went to "Add-New Item", the option to create either a new c++ file(.cpp) (creates a file with c++ source code) or a new Header File(.h) (creates a c++ header file) was offered. The first go around I ran w/ c++ file then attempted the illustration above. When that didn’t work I deleted add.h then deleted the [#include "add.h"], and reran main with the function prototype and it was successfully executed. Again I got the output
    "the sum of 3 and 4 is : 7
    Press any key to continue . . ."
    Then I went back through and this time wrote add.h as a header (.h) file. I made sure this was included in the main solution then ran it as prescribed (took out the function prototype and added the #include "add.h") and voila-same thing. Can you help? thanks Alex.

    • Alex

      > It shows it as an add.h.cpp file

      This is the problem. For some reason, your add.h file is named add.h.cpp. It has the wrong extension, so your code can’t find it. Rename it add.h and I think it will work.

  • Andrey

    One has to be amazed with the amount of patience this guy, Alex, demonstrates answering all kinds of questions here over the years 🙂 Great job, man! Also, very neat tutorial - thanks! I do have some Java background so I know my way around when it comes to programming, but C++ has some of its own perks (like this headers for example) and since this tutorial is so well organized, I had no problem finding what I need.
    So, once again - tnx to Alex (& the rest of the crew, if there is one :p )

  • Nico

    i figured it out. well not really, but i got it to work.
    seems like you need to add the files to your project, it does not do this automatically 🙂

  • Nico


    thanks a lot for this tutorial! however:
    i copy/pasted everything, and get the following error:

  • soumya

    Thanks Alex for such an informative tutorial. 🙂
    Really it has helped me a lot. But I have a question -
    I use turbo c++ for implementing c++ programs. As header files just contain function declarations and not their definitions, can you please tell me where will I find definitions ( function body  ) of these standard library functions in turbo c++ ?

    • Alex

      As far as I know, no compilers contain definitions for the standard library functions. Instead, the standard library is precompiled into a library that is linked into your program.

      This prevents the compiler from having to recompile the standard library every time you use it.

      • Devashish

        But I find istream, ostream, iostream etc. in my C drive where I installed MingW (as part of code::blocks) on my PC. I am not sure if everything (of standard library) is present there, but I can see some of the header files. I found cases where my code gives error and open a new file to show how things were implemented and what I am doing wrong.

        Alex, a short non-C++ question 🙂
        I am learning Qt (with C++, a lot of concepts are still not clear to me in C++). When writing my own SGNALS and SLOTS, I will (definitely) need some of the predefined classes to be included in my C++ source file. I see, that some of the examples in are written by including each header files (like QPushButton, QSpinBox etc.) individually where they can #include at once. What’s the reason behind that. I personally won’t write that much of code if a one line code can do the same thing for me.
        Thanks in advance….

        • Devashish

          I mean where they can write #include QTGui once. I wrote QTGui also in my comment above but enclosed them in angular brackets. I think that eaten up the header name.

          • Alex

            Header files yes, because those must in text format so they can be #included. So if there are functions defined in the header, you can see those.

            Generally you should only #include header files that contain the functionality you need. There are three reasons:
            1) Consider a .cpp file that needs A, B, and C, but not D or E. That file should #include A, B, and C. While it’s possible to make an all.h that includes everything, if you do that, any time you change A, B, C, D, or E, all of the files that include all.h will need to get recompiled too. For external libraries, like QT, this isn’t as big a deal.
            2) All of that code you #include gets compiled into code that bloats the size and memory requirements of your executable.
            3) Anybody looking at the top of your file would have no idea what dependencies your file really has.

            #including QTGUI will include about 350 other header files! You’re probably not using most of that, so why include it?

      • soumya

        But if there are function declarations , then there must be their definitions too.

        Actually there are few library functions like :
        In case of file handling we use read () and write()  for reading and writing class or structure objects into a binary file.
        Ifsream fin ;*) & obj , size of ( obj ));
        // consider that obj is an object of class student.

        So I wanted to know why this type casting (char *) has been doneand why & is used with obj ??

        And for this reason I was wanting to see  the definition of these functions.

        Can you please help me out with this? And also please let me know where these function definitions are present?

        • Alex

          The definitions are precompiled into binary format and are not human readable.

          We’ll talk about what type char* is (a pointer to a character) and what & means in this context (take the address of) in later lessons.

  • thank you Alex……….this page is very useful for people like me

  • gunty



    and fuggvenyek.h:

    When I debug my program, I get these errors:

    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(5): error C2065: ‘cout’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(7): error C2065: ‘cout’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(12): error C2065: ‘a’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(12): error C2065: ‘szam’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(13): error C2065: ‘a’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(13): error C2065: ‘a’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(13): error C2065: ‘a’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(13): error C2065: ‘a’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(14): error C2065: ‘a’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(21): error C2065: ‘cout’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(22): error C2065: ‘cout’ : undeclared identifier
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(22): warning C4554: ‘<<‘ : check operator precedence for possible error; use parentheses to clarify precedence
    1>d:visualc++_workspacenumereconsecutivenumereconsecutivefuggvenyek.cpp(22): error C2065: ‘szam’ : undeclared identifier

    If I put both .cpp files in one, the program is working. Why? I don’t understand.

    • Alex

      I see the following errors:
      1) Fuggvenyek.cpp uses cout but does not #include iostream.
      2) function keres() uses variables a and szam without defining them (you defined them inside of function main(), which keres() can’t see).
      3) You call cout inside of a function instead of std::cout (or add a using statement to each function that uses cout)

  • Unknown

    if we have a project that just need a header for example A.h.
    what will happen if we #include A.h and B.h and the project doesn’t even need B.h?

    • Alex

      It will pull all the declarations from B.h into the project anyway, but they won’t be used for anything.

      Note that the declarations in B.h could cause naming conflicts with declarations in A.h, if there were any conflicting identifiers.

  • Hi Alex,
    Is there any update library for socket programming in C++ ?
    How I can get it ?


  • Luis77

    Thank you very much for your answer, Alex.

    I will firstly head for solution #2. Then, I am going to learn about libraries and then switch to solution #3. By the way, is there a chapter on this website about library creation ? (appendix A is only about using libraries not creating them)

  • Luis77

    I would like to make sure I have correctly  understood this chapter, as I am new to C++
    I am using Code::Blocks as C++ IDE.  

    I need to create some mathematical functions that I am going to use in a lot of projects (present and future). e.g.: distance between 2 points, norm of a 3D vector, scalar product, and so on…
    All these functions are related to the mathematical field of geometry. That is why I wrote them in a single *.cpp file called mymathgeom.cpp:

    I have created the corresponding mymathgeom.h file:

    Those 2 files are located in a folder I defined as a general search path in Code::Blocks (not only for one project but for all). The other *.h files I am going to create in the future will be stored in the same folder.

    My first question is: is it a good practice to write several functions to be reused in the same *.cpp file ? Or is it better to write each function in a separate *.cpp file ?

    Then, from each project point of view:

    1) I have to #include "mymathgeom.h" at the beginning of my main.cpp file.
    2) I have to add mymathgeom.cpp to each project.

    Is it right ? What seems a little bit strange to me is point 2): I had to do that in order to build and run my project. But that means that mymathgeom.cpp is compiled every time I compile my project. Is that efficient ? or is there another way to do ?

    Thanks in advance

    • Alex

      Definitely don’t write each function in a separate file. That would be an organizational nightmare. 🙂 Best practice is to put related functions into the same .cpp file -- so all of your geometry functions would be a great fit for a geometry.cpp/.h file.

      As far as including your geometry functions, you really have 3 choices:

      1) Copy the files into every project you need them, and add them to your project just like any other project file. They do get recompiled for every project… but using precompiled headers, after you compile the first time they won’t get compiled again unless they change. The main downside here is that you’re duplicating files, which can make it hard to tell which file is the latest version.

      2) Store all your reusable files in one central location. Add the code files to your project like normal. You can #include the headers like normal, but you’ll need to add the location of the headers to your project’s include path. If you ever move your central files, this method is a pain.

      3) Precompile your code into a library and tell your compiler to include the library. You can #include the headers like in option 2. This is more of a pain, but makes it a little easier if you want to move where the library lives, as you only have to update the library path in your project settings.

      PS: Definitely check out structs (and later, classes). They’re great for handling points (and other geometry concepts, like vectors).

  • raph.ael

    question: i wanna use a *.h for file operations (create/open > updating/reading > close), do i include fstream at main.cpp or can i # in the header file, if im not using fstream for nothing else? can one option or another affect the performance in a good/bad way for build/running a long code?

  • Alex

    #pragma once is an alternative way to do header guards.

    Here’s my comment from lesson 1.10 on this topic:

    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.

  • Andy

    Hey Alex! 😀

    Yesterday I installed Visual Studio Community 2015 (the new version of Visual Studio Express).

    I just wanted to make the program from chapter 2.6 and I thought this would be a nice place to use multiple files and header files. When I created the header file it automaticly had "#pragma once" in it.

    A little googeling tells me that "#pragma once" is like #ifndef, but I’m not sure.

    What do you think about this? 🙂

  • Typo:
    "If you ever update your directory structure, you(‘r’ is missing here.) code won’t work any more."

  • Marc

    For the add.cpp, why don’t you include: #include "add.h" at the top of the file?
    Should it be this

    #include "add.h"

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

    • Alex

      In most cases, a given .cpp file will #include its .h counterpart.

      However, in this example, it’s not strictly necessary, because there’s nothing in add.h that add.cpp needs to reference.

  • Tomboy

    Thank you so much for this site! I have a question, if it’s not too stupid:

    Why do we put the forward declarations in a header file? Couldn’t I just put these forward declarations in a “declarations.cpp” file and include that at the top of the main.cpp file?

    • Alex

      C++ doesn’t care what files are named, so what you suggest would work (as would any other filename, such as “moo.asdf”). But I wouldn’t recommend it, because it violates common naming conventions, and there’s no benefit to doing so.

      There’s nothing inherently special about header files in C++. They just provide a useful and widely understood pattern for sharing declarations.

      • Tomboy

        Thank you for answering my question. I really appreciate the time you take to run this website and help people like me out 🙂

        I started to learn Visual Basic 6 back when it was so popular in the 90s and I’m trying (very slowly) to move over into C++.

  • Ismail Daif

    Hey Alex, first of all thanks for this great tutorial series, I’m loving it so far.

    You said: "When C++ was first created, all of the files in the standard runtime library ended in .h. Life was consistent, and it was good. The original version of cout and cin lived in iostream.h. When the language was standardized by the ANSI committee, they decided to move all of the functions in the runtime library into the std namespace (which is generally a good idea)."

    But from what I read, ANSI never standardized C++, ISO did. So was it the ISO committee that decided this, or was this perhaps during standardisation of C?

    • Alex

      The ANSI group was the first to standardize C++, which they started in 1990 and finished in 1998. ISO also approved this standard, making it an international standard.

  • Aakash Pandita


  • Aakash Pandita

    I am having trouble understanding what’s written under:
    Why doesn’t iostream have a .h extension?
    Can you explain it in a simpler way?
    If not what should I do?

    • Alex

      In the original version of C++, all of the functionality in the standard library did not live inside the std:: namespace. This means you could do this:

      Later on, they decided to move all of the functionality in the standard library inside the std:: namespace, in order to help prevent naming collisions.

      However, if they had changed iostream.h to implement this, the above program would no longer work! All programs written using the standard library (which is almost all of them) would need to be modified to accommodate this change. (Side note: I’m actually not sure why this was a big deal -- using declarations would have made this easy)

      So instead, they created an alternate version of iostream without the .h extension that includes all of the functionality in the std:: namespace. Programs written prior to the move could use iostream.h. Programs written afterward could use iostream.

      If this still doesn’t make sense, don’t worry about it. Just #include instead of and you’ll be fine. 🙂

  • Humphrey

    When you use a forward declaration to alert the compiler of a function not yet defined, while there is a function in another file with the same name but different definition due to the limited visibility in each file, what is the result?

    • Alex

      The forward declaration actually doesn’t matter in this example.

      If the two functions are declared in different files and neither function has visibility beyond that file, then the program should still compile.

  • Drew

    So I think I understand everything about this except for I don’t see you mentioning where the function definition lives. Are we including the file in the manner that you showed us in the last(ish) lesson? Are we defining it in main? Thanks.

    • Alex

      The function definition lives in a .cpp file. When your programs are small, this will be whatever you named your main .cpp file. As your program gets larger, you’ll probably want to have matched pairs of .cpp and .h files (e.g. all your math functions go in math.cpp and the associated declarations in math.h).

      • Drew

        Ok. So just to make sure I’ve got this straight…

        Using the examples from this lesson we would define the add function in add.cpp, add that file to our current project main.cpp, then write the function prototype in a header file named add.h which we only have to #include as opposed to adding it in the manner you showed in 1.8? And therefore you never have to type out the function prototype or definition in main.cpp because it’s being included from other files?

        • Alex

          You got it. When you #include add.h, it’ll bring the forward declaration for the function declared in add.h into the current file, allowing you to use the function.

          This method is super useful when you have a function or set of functions that you need to use in a lot of places.

  • bhawna vohra

    plzz help me asap
    i m not getting whether to use 3 programs 2 mentioned above and another one for header guard?
    nd what how to solve this error:"as1stackq1 has not been declared"

  • Daniel W

    this one works:
    Create Interface ‘Cat.h’
    #include "stdafx.h"

    class Cat

        int GetAge();
        void SetAge(int age);
        void Meow();
        void Bark();

    Create Cat Implementation ‘CatImpl.cpp’
    #include "stdafx.h"
    #include <iostream>
    #include "Cat.h"

    using namespace std;

    class CatImpl{
        unsigned int Age;
        unsigned int Weight;
        int itsAge;

      CatImpl::CatImpl(int initialAge)// constructor of Cat,
             Age = initialAge;
        { }// destructor, takes no action
        int CatImpl::GetAge()// public accessors
             return Age;
           void CatImpl::SetAge(int age)
              Age = age;
           void CatImpl::Meow(){
             cout<<"This cat Meown";
                        }    // private member data
        void CatImpl::Bark(){
             cout<<"This cat BARKn";

    Create Main Class ‘SimpleClass.cpp’
    // SimpleClass.cpp : main project file.
    #include "stdafx.h"
    #include <iostream>
    #include "CatImpl.cpp"

    //using namespace System;
    using namespace std;

    int main()
    int x;
           CatImpl Frisky(50);
       // Frisky.SetAge(5); // assign to the member variable
        cout << "Frisky is a cat who is " ;
        cout << x<< " years old.n";
        cout << x<< " years old.n";
    cout << x<< " New Age.n";
    cout << "n";

        return 0;

  • Please kindly assist with the below programme. It does not compile and run. I have tried all I know. Many thanks!!!!

    //Display 10 random numbers.cpp
    #include <iostream>
    using namespace std;
    int main()
    int r;
    for (int i=0; i<10; i++)
    cout<<"The number is: "<<r<<endl;
    return 0;

  • Hi Alex,

    My question may sound dumb, please pardon me!
    Initially in some chapter, I read that the namespace "std" contains the "cout", if this namespace is not used in the program, the compiler will not know what "cout" is.
    Now, in the very first program in this chapter, you told that iostream is the header which declares the "cout".
    You also told that the definition of cout is provided by the C++ runtime library.
    So, what exactly does the namespace do?

    Thanks in advance,

    • I somehow, able to figure this out when I read the section "Why doesn’t iostream have a .h extension?"

      So, iostream has the declaration of cout and its definition resides in the namespace "std" which itself is a C++ runtime library.

      Is my statement correct?

      • Alex

        Very close. Iostream.h contains the declaration for cout, which is inside the std namespace. The definition of cout lives in the C++ runtime library, which is linked into your program when you compile it.

        • Thanks Alex, that was helpful!
          Just out of curiosity, is there any way to see the contents of std namespace? Or, is it hidden from a programmer?

          • Alex

            If you want to know what’s in the std namespace, you’re probably best off looking at external documentation.

            By viewing the header files that are part of the standard library (e.g. iostream), you can see all of the declarations that are part of the std namespace. But those files tend to be complicated, so don’t be surprised if they’re basically unintelligible. 🙂

  • Brandy C. Z.

    Hello, could you please help me, not sure where I’m going wrong here.  My code is different but it worked before I tried to move my function to another .cpp and .h

    My main

    Then here is my source file getX.cpp

    And lastly the header file getX.h

    And here are the errors I get:
    1>---- Build started: Project: tutorial quizzes, Configuration: Debug Win32 ----
    1>  tutorial quizzes.cpp
    1>c:\users\brandyc\skydrive\documents\tutorial quizzes\tutorial quizzes\getx.cpp(1): error C2006: ‘#include’ : expected a filename, found ‘identifier’
    1>c:\users\brandyc\skydrive\documents\tutorial quizzes\tutorial quizzes\getx.cpp(1): fatal error C1083: Cannot open include file: ”: No such file or directory
    1>  getX.cpp
    1>c:\users\brandyc\skydrive\documents\tutorial quizzes\tutorial quizzes\getx.cpp(1): error C2006: ‘#include’ : expected a filename, found ‘identifier’
    1>c:\users\brandyc\skydrive\documents\tutorial quizzes\tutorial quizzes\getx.cpp(1): fatal error C1083: Cannot open include file: ”: No such file or directory
    1>  Generating Code…
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

  • Josh

    Follow description maybe incorrect, as far as I known, read/load all the file context from header file stuff should be done by c++ preprocessor, but not compiler. 🙂

    When we use the line #include <iostream>, we are telling the compiler to locate and then read all the declarations from a header file named “iostream”.

    • Alex

      You are correct, it is the preprocessor that includes all of the content from the header file.

      I’ve updated the wording in this section to be more agnostic of how #include works, since I don’t introduce the preprocessor formally until the next section, where it’s discussed in more detail.

  • Daniel

    Hello Alex,

    When I try to run the main.cpp using your example code I get an error unless I have #include "stdafx.h" in add.cpp.

    I think all files are created correctly, when I open main.cpp the 2 .cpp and .h appear.

    any suggestions?



    • Daniel

      Again doesn't matter,

      Have just realised I was being an idiot!


      • Alex

        Just in case anybody else runs into the problem, if you’re using Visual Studio with precompiled headers turned on (which they are by default), you need to #include “stdafx.h” at the top of all your code files, otherwise Visual Studio complains.

  • i just don’t get it, are headers there for declaring only?

    i mean i made this program with one function and i didn’t declare it i just defined it in the header file, included it in the cpp file and it worked fine, so why your headers are used for declaring only??
    is there something wrong with defining the functions in the headers with out declaring them at all?


    #include "main.h"

    using namespace std;

    int main()
    int uservalue=0;
    cout << "enter a value:" <> uservalue;
    cout << doubleIt(uservalue) << endl;
    return 0;


    int doubleIt (int x)
    return x * 2;

    • Alex

      I just updated the tutorial to cover this topic, because it’s one that gets asked fairly often.

      In short, while it’s something you can do, you generally shouldn’t, because it’ll increase your compile times and bloat the size of your executable.

  • rubcaspac60

    Good day,

    I am having a really GOOD time with this tutorial, but I am stuck in a part which is really silly, but at this point my frustration is too big and I need a solution. I am trying to add the “add.h” header and I have tried several times to compile and run, but my function “main” seems not to recognize the intrusion of “add.h” header.

    I get this result:
    ||=== Build: Debug in Lesson1.9 (compiler: GNU GCC Compiler) ===|
    obj\Debug\main.o||In function `main’:|
    E:\Documents and Settings\Owner\My Documents\Dropbox\Dropbox\Lesson1.9\main.cpp|7|undefined reference to `add(int, int)’|
    ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

    At this point I re-built everything from scratch and I do know now what is the problem.
    I am using Code:Blocks 13.12 as my IDE.

    Please help… I do not want to end the fun.


    • Alex

      It looks to me like maybe either you didn’t #include add.h from main.cpp, or there’s a typo somewhere in add.h so that the prototype for function add() is incorrect (e.g. the function has the wrong name).

  • Ciprian

    Just AMAZING, this tutorial . .

  • rodrigor

    This is probably the most comprehensible C++ tutorial I have read. I’ve worked with the C++ language on and off for sometime now, and I’ve never found material has was able to explain the missing bit of information that I needed, such as the explanation behind #include <include> vs #include <include.h> which has been bothering me for years not to mention your C++11 section. Thank you for this amazing site.

  • lilith

    Now I have created the header file and still get the same error:

    main.o: In function `main’:
    main.cpp:(.text+0x14): undefined reference to `add(int, int)’
    collect2: error: ld returned 1 exit status

    The compiler doesn’t find the add() function, neither with forward declaration nor using a header file. My code is an exact copy of your example and split in 3 files, main.cpp, add.cpp and add.h. Also, I have put all three files in the same directory, it contains only those three and nothing else.
    Where am I going wrong?

    • lilith

      Ok, I’ve solved my problem myself. It didn’t have anything to do with the example code, but simply with my lack of knowledge of g++.

      For any of you running into the same problem:
      g++ -c main.cpp
      g++ -c Complex.cpp
      g++ main.o Complex.o
      This does the trick. Next, if you check the contents of your source file, you see an executable named “a.out”, which you have to call (“./a.out”) to run your code.
      Everything peachy now, I finally can move on with this very helpful tutorial!

  • fantastic source code!hi every body!

  • lopata

    Now, i am mad with this tutorial.

    1st of all, please explaing with SIMPLE words what is this line suppose to do.

    #ifndef ADD_H
    #define ADD_H // Command to define header

    int add(int x, int y); // function prototype for add.h // definition

    #endif // end of defining.

    In my understanding this should create a header add.h and define it ? right or wrong.
    If I want to do it manually, I can create add.h and define it my self, so above stated example has no common sense in this world.
    Defined add.h can look like this

    int add(int x, int y); // function prototype for add.h // definition
    right or wrong?

  • Learner

    This is the best page so far! Ok, this is just the beggining of the tutorial, but it explains things I always had curiosity about: “Why to use header files?”, “Why the standard library is precompiled?”, “Why standard header files don’t end in .h?”. I appreciate very much how the topics are ordered and how the author answers all my doubts.

    • Why use header files - When you have 10k or more lines of code having it in one file is a royal pain. You use header files to split code between multiple files helping in both project management and code readability.
      Why is the standard library precompiled - The standard libs are large. Thousands of lines of code large. You do not want to recompile it every time you want to see whether your program works. That’s why they’re precompiled.
      Why standard header files don’t have the .h extension - some do. .h extension is useless and only wastes your time when you have to write it.

    • Alex

      I removed the section from this lesson on why the standard library is precompiled. It’s interesting, but a bit extraneous. If you want to learn more about libraries or why they are usually precompiled, that is covered in appendix A.1 -- Static and dynamic libraries.

  • ashik

    add.cpp must contain the “add.h” header, otherwise the declaration wont be found, happened to me

  • gu_obos

    As an FYI to anyone else having issues with Visual Studio 2012 and having issues with with building:

    If precompiled headers are turned on, you *must* have #include “stdafx.h” as the first include. Otherwise your includes don’t work.

    See this link for more info:

  • artxworks

    so add.cpp is still needed? since we don’t need to write the actual code in the header add.h ….

    #ifndef ADD_H_INCLUDED // I don’t know why it has that “ADD_H_INCLUDED
    #define ADD_H_INCLUDED // same for this one and the #endif …. can I change it to other names??? say ADD_H_WHATEVERIWANTHERE???

    int add(int x, int y);

    #endif // ADD_H_INCLUDED

    I tried it in Code::Blocks and it worked! XD

    • john

      Im new to code blocks
      Also tried this in Code::Blocks used

      #ifndef ADD_H_INCLUDED
      #define ADD_H_INCLUDED

      int add(int x, int y); // function prototype for add.h

      #endif // ADD_H_INCLUDED


      #include “add.h” // this brings in the declaration for add()

      int main()
      using namespace std;
      // cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
      return 0;

      build gave an undefined reference error as is couldnt find add

      It looks like its not picking up the directive to find add.h
      Obviously doing something wrong, can you please help

      • rameye

        Where is your add.cpp file? Did you create it and add it to the project? If not it will not be compiled during the build and then the linker will not find the add function, thus the “undefined reference” error.

  • yuvadius

    why would a header file include another header file?
    arn’t you supose to just declare stuff in a header file.
    in that case i don’t see why header file will even include another header file

    • rameye

      You are correct, header files are for containing forward declarations to things that exist outside of your .cpp file.

      However, what if the forward declarations in the header file also make reference to outside things? Perhaps the forward declaration’s return type, or it’s parameter types, need also to have their own forward declarations.

      This is why a .h header file would include more header files, to bring in those forward declarations of things referenced in it’s own forward declarations.

      Also a header file may make use of constants, and those constants may be declared in another header file that must be included.

      • Alex

        This is correct. It’s not uncommon for header files to include other header files that contain things they need.

        For example, lets say you have a function prototype that looks like this:

        std::string sayHi();

        How does the compiler know what std::string is? This header will have to include <string>

  • Nitin

    amazing i find this website to be very helpful

  • Madeinqc

    This was way more clear than college, helped me out a lot.

  • donblas

    i guess im the only one getting this problem. visual 2005 express user. im doing everything, even copied the examples, and its giving me the error: precompiled header file is from a previous version of the compiler, or the precompiled header is C++ and you are using it from C (or vice versa)
    can anyone solve this?

  • Pratik Patel

    In header add.h, add() is not defined, that’s why many of you are having an error…

    • Alex

      > In header add.h, add() is not defined

      That’s intentional. In header files, we typically only declare functions, not define them.

      Add.cpp defines the add() function. Most people who are having problems aren’t including add.cpp in their projects, so the definition of add() is not being linked into their programs.

  • zamanengineer001

    what is functionality of these lines in add.h file:
    #ifndef ADD_H
    #define ADD_H

  • Lakshya

    Tried a lot but got errors. Finally figured my header file name was not add.h but something else. Phew!

    • Alex

      Some IDEs won’t add an extension to your header file if you don’t specify one, and some will. So if add.h doesn’t work, see if your IDE named the file add (no extension), or maybe add.hpp.

  • SWEngineer

    Excellent tutorial, explained in a simple manner. Thanks a lot.

  • PsyberMind

    So is it a safe assumption that headers are actually prepended to the top of the entire code? (Hence the term header) and the reason why you don’t need to forward declare the function before the main() function?

  • Billywilliam

    Sup dudes. After a good hour of troubleshooting I finally put add.h, add.cpp, and main.cpp all into the same project/folder (I’m using 2010), and i compiled it and it worked fine.

    Then I ran it and it’s giving me this error message:

    mainmain.obj : error LNK2019: unresolved external symbol “int __cdecl add(int,int)” (?add@@YAHHH@Z) referenced in function _main


    C:\Documents and Settings\hunter\My Documents\Visual Studio 2010\Projects\mainmain\Debug\mainmain.exe : fatal error LNK1120: 1 unresolved externals

    I went ahead and defined add in the header file (add.h) and ran it and it worked fine, so there isn’t really any problem.. I just want to know how to do what Alex is doing. I’m only 15 but I’ve been told I’m a pretty sharp kid .. so it’s bothering me that I havn’t been able to figure this out in 45 minutes.
    help pl0x

    • Alex

      The linker is complaining it can’t find a definition for function add(). Odds are you either forgot to include add.cpp in your project (even though it’s in the right directory), or it’s not compiling/linking for some reason (check your project settings and make sure the file isn’t being excluded from compilation)

  • baz

    Thanx Alex you are certainly a king amongst men, and patient with us newbies. Because I was forever #including the other .cpp in the main.cpp and getting a linker error. It kept saying I had declared a function twice: in the header file and main.cpp!

    In desperation, sometimes I did not include the header file in the main.cpp, in hope it would compile and link. I read your tut twice and began looking through my code and then realised I was declaring it twice, when I #included the other.cpp in which the offending function was declared, in the main.cpp where it was called.

    My bad. Thanx for a great tutorial.

  • masud

    Thanks for this tutorial……….

  • Finally some basic information on how to use .h files! It should be mandatory for anyone who wants to write a tutorial on C++ or some equally technical subject to study the style in this tutorial before they do so.

    I escpecially like the flowcharts. While being extensive, they still aren’t overwhelming.

  • Jeff Johnson

    I’m getting this error

    Compiler: Default compiler
    Building Makefile: “C:\Dev-Cpp\”
    Executing make…
    make.exe -f “C:\Dev-Cpp\” all
    g++.exe -c ADD.cpp -o ADD.o -I”C:/Dev-Cpp/lib/gcc/mingw32/3.4.2/include” -I”C:/Dev-Cpp/include/c++/3.4.2/backward” -I”C:/Dev-Cpp/include/c++/3.4.2/mingw32″ -I”C:/Dev-Cpp/include/c++/3.4.2″ -I”C:/Dev-Cpp/include”

    g++.exe main.o ADD.o -o “Project1.exe” -L”C:/Dev-Cpp/lib”

    ADD.o(.text+0x100):ADD.cpp: multiple definition of `add(int, int)’
    main.o(.text+0x100):main.cpp: first defined here
    collect2: ld returned 1 exit status

    make.exe: *** [Project1.exe] Error 1

    Execution terminated

    I’m using bloodshed

  • poornima

    Is it possible to use $ sign in the place of angular brackets in the header files section.
    ex:#include$stdio.h$ instead of general usage of

  • akhileshr7

    Thanks Alex! Nice tutorial.

    I’m learning c++ and having tough time compiling the following code. Can some please help?

    This is the error i’m getting -

    $ c++ main.cpp
    /tmp/ccKDQaIR.o(.text+0x128): In function `main’:
    : undefined reference to `add(int, int)’
    collect2: ld returned 1 exit status

    This is my code -




    This is the version of my c++ compiler -
    gcc version 3.4.6 20060404 (Red Hat 3.4.6-9)


  • Kraig

    For those of you who are using Visual Studio and are getting errors. This will fix it!!

    First off you don’t need add.cpp, because add.h is your”library for the function”
    -If you are following along with the tutorial you need to edit the add.h file.
    -It needs to be as follows:

    Reason for the change…a function must be declared in order to work.

    • codechick

      Hi Kraig! (from Kraig’s answer on July 22, 2010 at 6:57 p.m.)

      You are the BOMB! Your answer is perfect and solved my problem perfectly.
      I had that hinky feeling the code was jacked up, however, I was so absorbed
      in learning how to use header files, I didn’t come up with it.
      For the record, I’m using DevCPP and your answer of adding the “return” statement
      to the code in the header file is the solution, thanks again!

      • Alex

        This works, but I generally wouldn’t advise it.

        If you define your function in the header file, then the full definition of that function will be copied into EVERY file that includes it. For trivial functions that may not be much of an issue, but for larger files this can bloat the size of your code significantly.

        The root of your problem is likely that you didn’t include add.cpp in your project file. Fix that and you don’t need to define the add() function in the header.

  • Eric

    So I’ve been mulling this over and bare with me because I’m somewhat new to all of this, but is the function of a header just to clean up your code in your “Main.cpp” file? Is it just basically to move all of the forward declarations to that file rather than have them all declared in your main file? Things like this likely would become more apparent when working with a bigger more complicated program, it just seems like overkill when you only have to make forward declarations for 1 or 2 functions.

  • Wally

    I’m working with Code::Blocks and no matter how I create a ‘.h’ file the compiler renames it *.h.gch and then complains that file format is not recognized.
    For instance I go file-new file then whether I select all files or C/C++ header file, or whether I add ‘.h’ manually the result is the same. I can’t save as and change it, the result is the same.
    What can I do? HELP!

  • Andy

    i am making multiple files copying what the tutorials say, and here is the code i have input:

    here is main.cpp:

    And here is what happened when i built it on VC2008:

    ---- Build started: Project: add, Configuration: Debug Win32 ----
    c:\users\andy\documents\visual studio 2008\projects\add\add\main.cpp(5) : error C2144: syntax error : ‘int’ should be preceded by ‘;’
    Build log was saved at “file://c:\Users\Andy\Documents\Visual Studio 2008\Projects\add\add\Debug\BuildLog.htm”
    add - 1 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Where did i go wrong?

  • TeenChristian

    Hi 🙂 wonderful tutorials!
    Just one question… When I make an “add.h” header file and copy and paste the good on the tutorial for both the main .cpp file and .h file it still gives me these errors: ‘std’ a namespace with this name does not exist, ‘cout’ undeclared identifier, ‘endl’ undeclared identifier’


    thanks in advanced 🙂

  • At first I confused why my header program didn’t work, but finally I knew i have to used stdafx 😀 😀

  • Bryan

    I have to say that these are very helpful tutorials as it explains things MUCH clearer than what I have been getting in college. I’m learning the C++ object oriented programming form for game programmers. So the fun is immense. Working with classes, headers and the main has been tormenting me. And now slowly falling behind I’m running low on time as now I have to work with random number generation. I definitely will be making full use of this site, but Thank you again for a very clear tutorial on headers, I’m slowly making headway on this homework.

  • I actually figured it out. It appears that within project explorer, you can right click the file and select properties. It’s important to make sure that under the Build tab, the Debug and Release boxes are checked. Apparently, when I created the file I missed the step to check these boxes. All compiles as expected now.

  • So, I have been messing with the CodeBlocks Editor on Gentoo and the prototype definition doesn’t appear to pull in the add.cpp file. For this reason, when building, the build fails stating that add(int, int) is not defined. Now I’ve tried removing the header all together and place the prototype declaration directly above main.cpp and the build still fails stating that add(int, int) is not defined.

    I’m able to build from the command line by specifying:

    This process does not fail and creates the add.o executable, which runs correctly. Am I correct to assume this could be a bug in Codeblocks? So far I’m also pretty impressed with the tutorial. Thanks for your guidance Alex.

  • retro-starr

    I figured it out! So you need main.cpp, add.cpp and add.h all in the same folder because the main is including add.h which calls add.cpp to define what “int add()” is! Now my question is, how can you use files in different folders?

  • Luke

    Hi Alex - I’m having some issues with this -

    my code is identical to the website - and I have no add.cpp in this project
    when my code is this

    I get the error “add(int, int)” not defined

    but when I change to this

    it works

    I am guessing that this is because the header file only is added when ADD_H is included somewhere in main due to the if statements - but what happens when there is more than one function prototype in the library?

    • Alex

      I’m not sure why this is working for you. ADD_H should be meaningless.

      The header guard ensures that the header is not included more than once (that would lead to redefinition errors).

      You are allowed to have more than one function prototype in a header file.

  • Array

    Hey Alex, thanks for the awesome tutorial, i had major problems and confusions on how to actually write the header files, but now i understand it more. 🙂

  • Bladtman242

    Why actually make header files? why not just define the functions you need after main?

    • Alex

      In trivial examples like the ones we’re doing right now, there’s really no need for header files.

      However, once you get into writing more complicated things, you’ll use header files everywhere. They allow you to import a set of declarations to multiple source (.cpp) files with minimal effort.

      An analogy might be useful here: imagine every time you wanted to use std::cout, you had to copy every thing related to std::cout into the top of your .cpp. For every .cpp file. That would get annoying, right? Isn’t it much easier to just #include ?

  • CJ

    Hey Alex, these tutorials are awesome! :] I’m learning a whole lot.
    Thank you for making them.

    This is probably something really obvious, but I am really confused.
    I’m using Microsoft Visual C++ 2008 Edition, and when I add the add.cpp file, it automatically gives me an add.h file as well. But when I open it, in the tab it says add.h [Design] and there’s just a box named add, and I can’t put code anywhere.

    I realized that there is a seperate folder specifically for Header files, but I couldn’t create an add.h file in it, because the name is already used. So I created one with a different name (with a .h extension), and it gave me a .cpp and a .h for that, too. And the .h is still a design box.

    I’m probably going to feel really dumb after this, but where am I suppose to put the header code? D:
    I have like 8 files and I only need to use three…so confusing >:
    Also, the .cpp files had #include “theirname.h” on the top,
    should I leave that there?

  • nryoung

    Great tutorial and thanks for taking the time to respond to people’s questions. I have one myself. I am using Code Blocks 8.02 with Ubuntu 9.04.


    here is my add.cpp

    here is my add.h

    Now every time I try to build this program I get this error.

    any help with what I am doing wrong would be great. Thanks

    • I don’t see anything wrong with the code. Sounds like an OS-specific issue. Perhaps ask on a Ubuntu forum?

    • bansidhar

      For gcc compiler you may require to declare the function as extern “C” or the linker won’t link it properly. Try the following header file

  • rob s

    what does “int” stand for or represent?

  • Justin

    How do i create a header in Dev C++? your help would be appreciated

    • Tyler

      In order to create a header file in dev-cpp, in the upper-left corrner there is a ‘new’ button (button with a pic of a blank peice of paper on it), click on this. once the file is created, right click the filename in the left hand column, and select rename. Enter the new name for the file and put .h at the end of the name. This will state it as being a header file and thus cuase the linker to treat it as such.


  • Michael

    WOW!!!!!!! Finally I get it. I had to have a add.cpp file and a main.cpp file and a add.h file! I’m sure I’ll be reading all these tutorials over again because I can never understand everything the first time around even at a snails pace. Just knowing that I finally figured it out though is the best part and seeing my mistake from the last section makes it all the better. Thanks for the tutorials 🙂 I’ve gotten this far after my first day. But I’m sure I’ll be reading these tutorials over and over to fully understand everything! Thanks again.

    • csvan

      It is always a good idea to go over good, rich materials twice. I believe that the things you learn later on (not specifically in this tutorial, but anything) will help you better understand the basics when you go over them again. Generally, as you build a programmer mindset and learn to think, reason and think accordingly, I believe you will also find it easier to put things into perspective, so you might finally understand basic things you never understood the first thing you saw them.

  • 19bk87

    excellent tutorials(thank you!) but I have 3 questions.

    I don’t get the header file part.
    In the example you use add.cpp as the declaration for add(). In add.h you put in a forward declaration for add(). But why can’t you define add() in the header file, isn’t that more efficient since you don’t need add.cpp anymore and thus less files = less work.

    Second question (assuming you answered my first question):
    You use add.cpp as a declaration file for add(), is it common to use a .cpp file with more then one declarations? Meaning multiple function declarations in one .cpp file (seems more convenient) or do you have to use multiple cpp files for multiple function declarations?

    My last question:

    Will these tutorials lead to the explaination of actually using your knowledge of c++ in developing programs? I think that’s really important because: okay I learned c++, now how do I use my knowledge? Like this tutorial gives you an assignment to make a program in the end.

    Many thanks, keep it up!

    • You _could_ define add() in the header file if you wanted, but this is generally not done (unless the function is trivial, like 1 or 2 statements). Header files are generally used for prototyping functions and declaring classes, and then those things are actually implemented in .cpp files.

      It is VERY common to have multiple functions in one .cpp file. Typically a .cpp file will contain a whole set of related function (eg. math.cpp will contain functions to do square roots, exponents, and other mathy things).

      To address your last question, no, not really. It’s really up to you to figure out how to apply what you learn. At some point I’d love to go back and add that, but I haven’t had time. 🙁

  • sra1

    Never mind Alex I got it.
    This tutorial is really really helpful.
    I wish we have a tutorial for java too, please tell me if you have one…
    Thanks again.

  • SRA1

    Hi Alex,

    This tutorial is awesome and I cant believe I’m finally learning C++.
    I have a question. I was trying to compile the code you gave, it sounds crazy but should I add a header file in the header files folder or source files folder. Anyways I tried creating in both but none worked. I created the header file with .h extension.

    and the header file was

    I had an error:
    1>---- Build started: Project: HelloWorld, Configuration: Debug Win32 ----
    1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
    1>C:\Documents and Settings\sravan\My Documents\Visual Studio 2008\Projects\HelloWorld\Debug\HelloWorld.exe : fatal error LNK1120: 1 unresolved externals
    1>Build log was saved at “file://c:\Documents and Settings\sravan\My Documents\Visual Studio 2008\Projects\HelloWorld\HelloWorld\Debug\BuildLog.htm”
    1>HelloWorld - 2 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Please help I am badly stuck here.
    Thanks in advance.

  • Juan

    Amazing tutorials! It actually all makes sense LOL -- now do one on the economy for the new U.S. administration LOL Thank you very, very much for making these tutorials!!! Alex, is there a cd I can buy of these tutorials from you? Or a book you wrote? I would donate, but who knows, next week the website could be down 🙁

    • Sorry, there is currently no offline version of the site. It’s something I’d like to do but I just don’t have the time to put it together right now.

      This website has been running since May 2007, so we’ve been up for over a year and a half. As long as the meager advertising revenue exceeds the cost of hosting the site, it’ll probably be here. 🙂

  • Julian

    Header files sound really cool, because I could make a header file that had a function in it that would calculate the angle of the sun depending on the time/day of year etc, and put it on the internet for people to download 😛 (along with some instructions as to what functions to call in the main.cpp)

    I’m not advanced enough yet to calculate the angle of the sun but that would still be cool 😀

    I understand this whole tutorial.. except I couldn’t work out how to create a “.h” file :S

    I’m using Code::Blocks and when I create a new file it makes me save it as a “.cpp”

    Woooaahh nevermind, I just figured it out. 😀

    Awesome tutorials btw 🙂

    • Generally it’s a better idea to define your functions in .cpp files. If you wanted, you could distribute both the .cpp (containing the code) and a .h (containing a prototype for people to #include).

  • Tyler

    sorry about that last comment i figured out what i was doing wrong just as i finished posting it, i forgot to include the “using namespace std” thing. but now i have another problem: everything else comiles fine but i keep getting a linker error. it says that i have an undefined referance to add. i don’t know what i’m doing wrong.i’m using the same code only i fixed the “name space” issue and filled in all the missing ;’s at the end of some of the lines.

    • Did you actually define the add() function? If you defined it in another .cpp file (eg. add.cpp), are you sure you are compiling that .cpp file into your program? You probably need to add it to your project or compile command line.

      • Tyler

        so I need my main program, a header file, and a sepreate .cpp file to define add? and how would I include the .cpp file for the add function? would I just place it affter my ADD.h header file in the
        “# include” list? ex.

        • tyler

          so I made a .cpp file defineing add and included it in my program ( the .cpp file defining add is the same as the one in this lesson ). but when I tryed to compile the program, it gave me an error. it was complaining about a linker error to win16 or somthing like that. to be honest, i havent got the slihtest clue what it means by win16 ( exept that I think it might have something to do the windows operating system files???).

        • If you’re using a MS compiler, on the left hand side you should see your project and a list of all the files include in it. If you right click on “Source Files” and choose “add” you can add new files or existing files to your project. That’s where you need to add the file.

          Using #include with .cpp is almost never something you’ll have need of.

  • Tyler

    for some reason my compiler ( i’m useing bloodshed versoin 4.somthing )keeps saying that cout and cin are undeclared. i have wrote several programms before including fixeing Fluxx’s rectangle area calculator and they all have compiled and ran smoothly up until now. i have included both iostream and my own header file ( ADD.h ).here is my code:

    my header file for the add function is identical to yours ( only i named the file ADD.h instead of add.h ) .i have tryed rearanging them, retyping them, even writeing a whole new program. i’ve been stuck on this for days and i can’t see what i’m doing wrong. please help me Alex.

  • Richard

    Aaah. Nice one. Yes that worked a charm. Thank you Alex.

    So the compiling syntax is:

    C++ … -o out.exe

    where InlcudeN are the N additional header files to be read in mainfile.

    Is that a generic compiling syntax, or is this just specific to Cygwin???

    Thanks again!

  • Spock


    Thoroughly enjoying this tutorial too! Also the best I’ve seen so far online.

    I’m having some trouble compiling too!! I’m using a Cygwin bash shell

    I have 3 programs:

    The first is

    The next is

    and lastly I have add.h

    All files are contained in the same folder that I have been using for all my other programs.
    I have been compiling previous programs using c++ -o filename.exe

    The error message I get reads:

    “MYFOLDER/ undefined reference to ‘add(int,int)’
    collect2: Id returned 1 exit status


    If you can provide any advice here it would be greatly appreciated!


    PS I’ve tried changing to filename.cpp etc.

    • It looks to me like the linker can’t resolve the function call to add(), which means that you’re probably not compiling in properly. If I remember correctly, you should be doing something like this:

      c++ -o out.exe

  • funmi

    thanks for your tutorials. I mean not even c++ for dummies can touch this with the way u respond. 🙂 its helping me a great deal.

  • Alex

    Thanks for this tutorial, I have a question:
    I the second graphic, you showed the work of the compiler and linker with source files,
    Why there is not an arrow from add.cpp to add.h, since add.h is only declaration
    (which include function prototypes and variables) that add.cpp implemented?

    Thank you,

  • Niels

    In the actual add.cpp return (x + y) was stored.
    In add.h this sentence is not part of the code. How does the compiler/linker know that the sum of
    x + y is needed as the result?

    • When main.cpp #includes add.h, the function prototype for add() is imported into main.cpp. The compiler uses this add() prototype to ensure anyone calling add() is doing so correctly.

      Once the compiler is satisfied no syntax or type-checking errors exist, the linker takes over. The linker’s job is to combine all of the individual .cpp files into a single unit (generally an executable or DLL), and ensure that all of the function calls resolve to an actual defined function.

      If you forgot to include add.cpp in your project, your project would still compile okay (because the compiler could use the prototype to do type checking), but it would fail in the linker stage because the linker would be unable to resolve the call to add() to a specific function.

      • Girish Shetty

        Thanks Alex! I had this doubt while reading the tutorial. Greatly explained.
        Foremost, thanks a ton for such a wonderful tutorial.

  • Kameshwar Rao K

    Hello Alex,
    First of all I would like to thank you very much for taking time and posting such a wonderful tutorial. You have mentioned namespaces, but coming from ‘C’ programming background, I never came across ‘namspaces’. Can you please explain the basics and what these namespaces are? Thank you once again.


  • daneil

    i used the codes that you posted in the tuturial which are

    and since im using visual C++ 2008 i added #include "stdafx.h" to the top of the code but it always comes up with these errors

    1>---- Build started: Project: hmmm, Configuration: Debug Win32 ----
    1>c:my documentsvisual studio 2008projectshmmmhmmmhmmm.cpp(3) : fatal error C1083: Cannot open include file: ‘add.h’: No such file or directory
    1>Build log was saved at “file://c:My DocumentsVisual Studio 2008ProjectshmmmhmmmDebugBuildLog.htm”
    1>hmmm - 1 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    i have no clue what im doing wrong =/

    BTW so far the tuturials have been pretty good so thanks for taking your time to write it all

  • Daniel Passwater

    This is a great tutorial. Thanks for the time that you put into it.

    I’ve got a question: I’m working on a dialog in a solution (in VS 2005) that contains several projects. I’m trying to access one of the classes from another project, but I keep getting a linking error. I have done a #include “headerfile.h” and have added the path to my “Additional include directories” in the properties pages via the IDE. I’m unable to copy the .h file into my local directory, because it references a resource.h file located in it’s project. My dialog has a resource.h file of its own. Has anyone had a similar problem?

    • Generally you’ll get a linker error when you include all the appropriate header files but don’t include the actual definition of what’s in the header files. I’m guessing you need to include some of the .cpp files from the other project in the project you’re getting the linker error for.

  • Another interesting part of the tutorial. I learnt a lot about namespaces here. Thanks again for the great tutorial

  • Chase

    I use Bloodshed Dev-C++ and i keep geting these error messages while trying to compile: [Build Error] [Project1.exe] Error 1

    ld returned 1 exit status

    [Linker error] undefined reference to `add(int, int)’

    I copied the add header and saved it as a .h file in the same directory as the project. Has anyone else had this error? How can I fix it?

    • Chase

      Nevermind, I got it to work by changing the header from:

      add(int x, int y)


      add(int x, int y)
      { return x + y: }

      • TBM

        The problem Chase had here as do to the omission of the semi colon ” ; ” after his prototype for his header file and the reason it was fixed when he changed it was simply do to the fact that he defined it within the header itself instead of in a separate .cpp file.

        In other words his declaration should have looked like this in his header file:

        add(int x, int y); <-- notice the semi colon.

        When changed to:

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

        It was no longer a prototype but a definition, meaning that the add.cpp file was no longer needed do to the fact that the definition is also now held in the header file. At least this is my understanding so far.

        Oh, and yes I know his change uses a colon instead of a semi colon, I’m just guessing that it was a typo.

    • I had this problem too and couldn’t understand what was being wrong (I was trying out the IDE Geany).

      Until I realised that Geany didn’t compile both of the two .cpp files, and link them together.

      When I manually compiled/linked them with g++ it worked just fine.

  • Ewinz87

    Hmm, first of all great job with the tutorials. I have finally decided to familiarize myself with C++ and I really like it so far, however I’m a bit confused with this and have a question.

    So my question is the following: Should be include the header file for every source file (in this case I’m thinking about add.cpp or can we only use it for one source file. Also, isn’t it going to scream at us for “redefining?” the functions?

    Edit: I just found out. The header guard prevent that from happenning. As for using it in all the source files makes it easier and saves times?

    Excuse my english, it is not my native tongue. 😛

    • As you’ve noted, the header guards prevent the header files from being included multiple times. It’s a sloppy way of doing things, in my opinion, but it works and it’s the standard way to do it.

      Ideally, you should include your header file in every .cpp file in which you use the stuff it declares. However, in practice, since header files can include other header files, this may not be strictly necessary. For example, you might have a class named Foo that uses strings, so foo.h will include string.h. foo.cpp (which also uses strings) should ideally include both foo.h and string.h, but since foo.h already includes string.h, if you only include foo.h you will still be able to use strings.

  • jestuart

    Ok I have an issue here with the headers. I deviated from the last lesson slighy but it is close to the same. Please tell me where I went wrong with Header Files.

    Here is Program1.cpp

    Here is my output from VS2008:

    1>---- Build started: Project: Program1, Configuration: Debug Win32 ----
    1>c:\documents and settings\jstuart\my documents\visual studio 2008\projects\program1\program1\program1.cpp(18) : error C3861: ‘Multiply’: identifier not found
    1>c:\documents and settings\jstuart\my documents\visual studio 2008\projects\program1\program1\program1.cpp(19) : error C3861: ‘Add’: identifier not found
    1>c:\documents and settings\jstuart\my documents\visual studio 2008\projects\program1\program1\program1.cpp(20) : error C3861: ‘Subtract’: identifier not found
    1>c:\documents and settings\jstuart\my documents\visual studio 2008\projects\program1\program1\math.cpp(28) : 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:\Documents and Settings\jstuart\My Documents\Visual Studio 2008\Projects\Program1\Program1\Debug\BuildLog.htm”
    1>Program1 - 4 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • The problem might be that you named your math.h file math.cpp. Try renaming your math.cpp to math.h and see if it fixes your issue. If that doesn’t work, try reposting your problem in the forum. The forums don’t have any many problems with posted programs as wordpress seems to.

      • jestuart

        Spot on that worked. I changed MATH.cpp to Math.h and it worked fine. Thanks for the tutorial and the response Alex.

        • Abdul

          First of all thank you Alex for the excellent tutorials.

          a questions please:

          from jestuart’s code; I thought he will at least need three files, one for the header, one for the actual function and then one for main e.g
          Math.h - which contains the forward declaration
          Math.cpp - which will contain the actual function definition
          main.cpp - which will reference the .h files

          here is my code for a similar operation; using code::block


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

          int main()
          using namespace std;
          cout << "3 + 4 = " << add(3, 4) << endl;
          cout << "3 - 4 = " << sub(3, 4) << endl;
          cout << "3 * 4 = " << multiply(3, 4) << endl;
          return 0;


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

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

          int multiply(int x, int y)
          return x * y;


          #ifndef MATH_H
          #define MATH_H

          int add(int x, int y);
          int sub(int x, int y);
          int multiply(int x, int y);


          • isla

            thank you abdul for the code. i tried to run the code above, i am using codeblocks in Windows 7, but kept getting an error that says as follows:

            “undefined reference to `add(int, int)’
            “undefined reference to `sub(int, int)’
            “undefined reference to `multiply(int, int)’

            however, i was able to resolve this issue by adding this line of code

            inside the header file or the math.h file

            the following is the final code for the header (math.h) file:

            thank you for the nice tutorials everyone! 🙂

            • Alex

              It is bad form to #include .cpp files.

              It sounds to me like in this case, math.cpp wasn’t being compiled in the project. So instead, you have main.cpp #include math.h, which #includes math.cpp. This means the code from math.h and math.cpp get inserted into main.cpp. That defeats much of the point of having separate files.

              • Akash Aggarwal

                The problem here seems to be that math.cpp wasn’t added to the project correctly or not added at all. I ran into the same error while using command line when I did this:

                instead of:

      • jojo

        can you please explain that why we need to create add.h file when we have forward declaration?
        what is its main purpose?

        // This is start of the header guard.  ADD_H can be any unique name.  By convention, we use the name of the header file.
        #ifndef ADD_H
        #define ADD_H

        // This is the content of the .h file, which is where the declarations go
        int add(int x, int y); // function prototype for add.h -- don’t forget the semicolon!

        // This is the end of the header guard

        • Alex

          In the case where we have just one function we need to access from another file, we’d probably just use a forward declaration.

          But in code of sufficient complexity, we often have many related functions, all of which need forward declarations to be used, and we need to use those functions in more than one place. Header files vastly simplify that process.

          For example, it’s much easier to say, “#include ” than add individual forward declarations for functions named add, subtract, multiple, divide, square root, exponent, circumference, etc…

          • @ALEX..Lol then we can make another cpp file(A) where all the other functions’ forward declaration has been made, and forward declare (A) in the main program….Header files just make the compilation slower as each time the program compiles,all the data from the header file is simply copypasted…What is the main advantage of a header file?lol

            • Alex

              This won’t work -- you can’t forward declare a file. That’s what #includes are for.

              The main advantage of a header file is to import a set of declarations into any file that needs it. Header files typically contain forward declarations for functions defined in other files, as well as custom define types that need to be used (enums, classes, etc…).

          • By bad i mean i got it thanx

Leave a Comment

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