2.11 — Header files

Headers, and their purpose

As programs grow larger (and make use of more files), it becomes increasingly tedious to have to forward declare every function you want to use that is defined in a different file. Wouldn’t it be nice if you could put all your forward declarations in one place and then import them when you need them?

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. Header files usually have a .h extension, but you will occasionally see them with a .hpp extension or no extension at all. The primary purpose of a header file is to propagate declarations to code files.

Using standard library header files

Consider the following program:

This program prints “Hello, world!” to the console using std::cout. However, this program never provide a definition or declaration for std::cout, so how does the compiler know what std::cout is?

The answer is that std::cout has been forward declared in the “iostream” header file. When we #include <iostream>, we’re requesting that the preprocessor copy all of the content (including forward declarations for std::cout) from the file named “iostream” into the file doing the #include.

Key insight

When you #include a file, the content of the included file is inserted at the point of inclusion. This provides a useful way to pull in declarations from another file.

Consider what would happen if the iostream header did not exist. Wherever you used std::cout, you would have to manually type or copy in all of the declarations related to std::cout into the top of each file that used std::cout! This would require a lot of knowledge about how std::cout was implemented, and would be a ton of work. Even worse, if a function prototype changed, we’d have to go manually update all of the forward declarations. It’s much easier to just #include iostream!

When it comes to functions and objects, its worth keeping in mind that header files typically only contain function and object declarations, not function and object definitions (otherwise a violation of the one definition rule could result). std::cout is forward declared in the iostream header, but defined as part of the C++ standard library, which is automatically linked into your program during the linker phase.

Best practice

Header files should generally not contain function and variable definitions, so as not to violate the one definition rule. An exception is made for symbolic constants (which we cover in lesson 4.13 -- Const, constexpr, and symbolic constants).

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

In this example, we used a forward declaration so that the compiler will know what identifier add is when compiling main.cpp. As previously mentioned, manually adding forward declarations for every function you want to use that lives in another file can get tedious quickly.

Let’s write a header file to relieve us of this burden. Writing a header file is surprisingly easy, as header files only consist of two parts:

  1. A header guard, which we’ll discuss in more detail in the next lesson (2.12 -- Header guards).
  2. The actual content of the header file, which should be the forward declarations for all of the identifiers we want other files to be able to see.

Adding a header file to a project works analogously to adding a source file (covered in lesson 2.8 -- Programs with multiple code files). If using an IDE, go through the same steps and choose “Header” instead of “Source” when asked. If using the command line, just create a new file in your favorite editor.

Best practice

Use a .h suffix when naming your header files.

Header files are often paired with code files, with the header file providing forward declarations for the corresponding code file. Since our header file will contain a forward declaration for functions defined in add.cpp, we’ll call our new header file add.h.

Best practice

If a header file is paired with a code file (e.g. add.h with add.cpp), they should both have the same base name (add).

Here’s our completed header file:


In order to use this header file in main.cpp, we have to #include it (using quotes, not angle brackets).



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 forward declaration for function add, that forward declaration will be copied into main.cpp. The end result is a program that is functionally the same as the one where we manually added the forward declaration at the top of main.cpp.

Consequently, our program will compile and link correctly.

Best practice

A code file should #include its paired header file (if it exists). If you’re curious as to why, see nascardriver’s comment here.


If you get a compiler error indicating that add.h isn’t 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. Also make sure it’s sitting in the same directory as the rest of your code files.

If you get a linker error about function add not being defined, make sure you’ve included add.cpp in your project so the definition for function add can be linked into the program.

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 preprocessor 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 preprocessor that this is a user-defined 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.


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

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 that iostream.h is a different header file than iostream! To explain requires a short history lesson.

When C++ was first created, all of the files in the standard runtime library ended in a .h stuffix. Life was consistent, and it was good. The original version of cout and cin were declared in iostream.h. When the language was standardized by the ANSI committee, they decided to move all of the functionality in the standard library into the std namespace to help avoid naming conflicts with user-defined identifiers. However, this presented a problem: if they moved all the functionality into the std namespace, none of the old programs (that included iostream.h) would work any more!

To work around this issue, 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>.

In addition, many of the libraries inherited from C that are 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.

Best practice

When including a header file from the standard library, use the no extension version (without the .h) if it exists. User-defined headers should still use a .h extension.

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:

While this will compile (assuming the files exist in those relative directories), 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.

For Visual Studio users

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 the directories you’d like the compiler to search for additional headers there.

For Code::Blocks users

In Code::Blocks, go to the Project menu and select Build Options, then the Search directories tab. Add the directories you’d like the compiler to search for additional headers there.

For GCC/G++ users

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.

Headers may include other headers

It’s common that a header file will need a declaration or definition that lives in a different header file. Because of this, header files will often #include other header files.

When your code file #includes the first header file, you’ll also get any other header files that the first header file includes (and any header files those include, and so on). These additional header files are sometimes called “transitive includes”, as they’re included implicitly rather than explicitly.

The content of these transitive includes are available for use in your code file. However, you should not rely on the content of headers that are included transitively. The implementation of header files may change over time, or be different across different systems. If that happens, your code may only compile on certain systems, or may compile now but not in the future. This is easily avoided by explicitly including all of the header files the content of your code file requires.

Best practice

Each .cpp file should explicitly #include all of the header files it needs to compile. Do not rely on headers included from other headers.

Unfortunately, there is no easy way to detect when your code file is accidentally relying content of a header file that has been included by another header file.

Header file best practices

Here are a few more recommendations for creating and using header files.

  • Always include header guards (we’ll cover these next lesson).
  • Do not define variables and functions in header files (global constants are an exception -- we’ll cover these later)
  • Give your header files the same name as the source files they’re associated with (e.g. grades.h is paired with grades.cpp).
  • 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.
  • Be mindful of which headers you need to explicitly include for the functionality that you are using in your code files
  • Every header you write should compile on its own (it should #include every dependency it needs)
  • Only #include what you need (don’t include everything just because you can).
  • Do not #include .cpp files.
  • Order your #includes as follow: your own user-defined headers first, then 3rd party library headers, then standard library headers. This is a minor one, but may help highlight a user-defined header file that doesn’t directly #include everything it needs.

2.12 -- Header guards
2.10 -- Introduction to the preprocessor

500 comments to 2.11 — Header files

  • 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 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 :P (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 :D

    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. :D

    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. :P

    • 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 all code inside code tags: [code]your code here[/code]