Search

1.9 — Header files


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 forward 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. 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, our 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 are telling the compiler to locate and then read all the declarations from a header file named “iostream”.

Keep in mind that header files typically only contain declarations. They do not define how something is implemented, and you already know that your program won’t link if it can’t find the implementation of something you use. So if cout is only defined in the “iostream” header file, where is it actually implemented? It is implemented in the runtime support library, which is automatically linked into your program during the link phase.

A library is a package of code that is meant to be reused in many programs. Typically, a library includes a header file that contains declarations for everything the library wishes to expose (make public) to users, and a precompiled object that contains all of the implementation code compiled into machine language. These libraries typically have a .lib or .dll extension on Windows, and a .a or .so extension on Unix. Why are libraries precompiled? First, since libraries rarely change, they do not need to be recompiled often, if ever. It would be a waste of time to compile them every time you wrote a program that used them. Second, because precompiled objects are in machine language, it prevents people from accessing or changing the source code, which is important to businesses or people who don’t want to make their source code available for intellectual property reasons.

Writing your own header files

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:

add.cpp:

main.cpp:

We’d 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). 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:

add.h:

In order to use this header file in main.cpp, we have to include it. Here is the new main.cpp:

main.cpp that includes add.h:

When the compiler compiles the #include "add.h" line, it copies the contents of add.h into the current file. 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.

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. The double-quotes tell the compiler that this is a header file we are supplying, which causes it to look for that header file in the current directory containing our source code first.

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

Another commonly asked question is “why doesn’t iostream 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 <iosteam.h> do not need to be rewritten, and newer programs can #include <iostream>.

Make sure when you include a header file from the standard library that 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.

As a side note, many headers in the standard library do not have a non .h version, only a .h version. For these files, it is fine to include the .h version. Many of these libraries are backwards compatible with standard C programming, and C does not support namespaces. Consequently, the functionality of these libraries will not be accessed through the std namespace. Also, when you write your own header files, they will all have 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

Header file best practices

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

  • Always include header guards.
  • Do not declare variables in header files unless they are constants. Header files should generally only be used for declarations.
  • Do not define functions in header files unless they are trivial. Doing so makes your header files harder for humans to read.
  • 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.
  • Try to include as few other header files as possible in your header files.
1.10 — A first look at the preprocessor
Index
1.8 — Programs with multiple files

188 comments to 1.9 — Header files

  • 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>Compiling…
    1>Program1.cpp
    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>MATH.cpp
    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

          main.cpp

          #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;
          }

          math.cpp

          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;
          }

          math.h

          #ifndef MATH_H
          #define MATH_H

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

          #endif

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

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

  • Chase

    I use Bloodshed Dev-C++ and i keep geting these error messages while trying to compile:

    C:Dev-CppMakefile.win [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)

      to:

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

      • bucko

        Had same problem as Chase. his solution worked for me also. Thanks Chase

        • sam

          I had the same problem also and chases worked. and i see the following post by TBM clarifying you should have 3 parts. main.cpp, add.cpp and the add.h but this is not clear to me and others above me from the tutorial.

          By the way I would like to add this is by far an amazing tutorial and I have learned alot being new.

          Thank you very much.

          Best Regards

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

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

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

  • daneil

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

    #ifndef ADD_H
    #define ADD_H

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

    #endif
    and in the other file
    #include <iostream>
    #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;
    }
    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>Compiling…
    1>hmmm.cpp
    1>c:\my documents\visual studio 2008\projects\hmmm\hmmm\hmmm.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 Documents\Visual Studio 2008\Projects\hmmm\hmmm\Debug\BuildLog.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

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

    Kkamudu

    • I cover that topic in lesson 7.11 on namespaces. Even though it’s in chapter 7, any readers who are curious might have a look now — I think it will be pretty comprehensible even with just the knowledge presented in chapter 1.

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

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

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

  • funmi

  • Spock

    Hey,

    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 main.cc:

    The next is add.cc

    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++ filename.cc -o filename.exe

    The error message I get reads:

    “MYFOLDER/cc9iZFXR.0:main.cc(.text+0x13b): undefined reference to ‘add(int,int)’
    collect2: Id returned 1 exit status

    ****************

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

    Rich

    PS I’ve tried changing filename.cc 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 add.cc properly. If I remember correctly, you should be doing something like this:

      c++ main.cc add.cc -o out.exe

  • Richard

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

    So the compiling syntax is:

    C++ mainfile.cc Inclue1.cc Include2.cc … IncludeN.cc -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!

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

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

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

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

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

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

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

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

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

  • mada

    hi it is my first project i need to add header files after #include “stdafx.” i am working on vs2005 my code

    all of header files are stored in the same folder with the rest of project

    THE PROBLEM:

    while bulding this message
    Error 2 fatal error C1083: Cannot open include file: ‘image.h': No such file or directory c:\documents and settings\xppresp3\my documents\visual studio 2005\projects\segc++\segc++\segment-image.h 23
    i hope answer very fast.
    thanks

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

      -Tyler

  • rob s

    what does “int” stand for or represent?

  • Kenneth Redmond

    Alex, this is an awesome website, thanks for making it available.
    My question is if the function file needs the stdafx.h header in microsoft visual basic 2008?

    [ I have no idea, I’ve never used visual basic before. -Alex ]

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

    main.cpp

    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

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

  • SALAM
    THIS IS VERY IMPORTANT AND AMAIZING
    IT IS IN VERY SIMPLE FORM THAT ANYONE CAN UNDERSTAND
    I REALLY APPRICIATE AND THATNKS TO THE AUTHOUR

  • nine

    I was sent a .hpp file with nothing else and was wondering how to execute or read it or anything. Thank you for any help.

  • Alex

    Did you mean to write or in that short “History lesson”?

    (The part that sticks out, just to make it easier to find for you)

  • Bladtman242

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

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

  • ahashmi

    Hi guys,

    The article confuses me when it talks about the history what happened when C was standardized. I think the confusion starts when you introduce the runtime library, the built-in header and custom header, and the two .cpp files. Further, there is this step called linking and then the executable.

    Now I am a programmer in JavaScript so I know some things. However, I was under the assumption that I could have a library of predefined and predeclared functions and just start using them or borrowing them in my core cpp files. But this wrap up seems to disturb my judgement and I am like what? Can someone explain the theoretical meaning and purpose of each file/header/component? How are they related to libraries/dll(s)? And so on.

  • Sam

    Alright, I am a slow learner so I am rereading chap 1-5 again. hard thing for me to grasp is the breaking it down into functions. This program below is only way I could figure out how to get it to work. also i cannot figure out how to switch it from char to string and pass the info to another function:

    MAIN.CPP

    GENERATE.CPP

    RESULT.CPP

    GENERATE.H

    RESULT.H

    This Program works outside the compiler warning about whitespaces in GENERATE.H. outside of that it runs and functions. This program was alot easier to write it all in main() then to break it up into functions lol. but I am really trying to grasp functions cause it is the correct way from the tutorial to do it in the long run.

    So if you can critique me, I could learn by example.

    Best Regards

    ps: below is program all in main()

  • Sam

    Sorry about the above. I just noticed I should of posted this to forums. its a little past topic of where this tutorial is at presently.

  • thangavelu

    i am not to understand the header files then,please listout the header file names.

  • i have made a main.cpp program that call a sum function .
    i also define a header file add.h.also include this in main.cpp.
    but error is coming.
    please send me egg. of these type program i shall highly tham=nk full to you.

  • Dear Alex,

    Thanks a million for this comprehensive and thorough C++ course!

    Unfortunately, I got stuck on this chapter, because it wasn’t clear to me I had to include the add.cpp file along with the header; I thought the header replaced the add.cpp file.

    I got it now, though.

  • Andrei

    “This way, older programs that include

    do not need to be rewritten”

    You write this towards the bottom of the page… not that it matters but I’m a stickler for little errors… you meant to write “iostream.h” and you wrote “iosteam.h” (you missed the “r”)… just thought I should let you know :)
    so far a WONDERFUL C++ course… very easy to understand, wonderful examples, and I’m able to fly though it :) thank you

  • Kevin

    When I compile, I get this error:
    [Linker error] undefined reference to `__cpu_features_init’

    What do I do?

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

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

  • Ehsan

    Hi

    I have these files :

    – node.h:

    – node.cpp:

    – main.cpp (containing int mian())

    Now, which one shoud be included in mian.cpp? (I use g++ in order to compile main.cpp)

    • Ehsan

      Someone answer me please (as soon as possible)

      When I include node.cpp in main.cpp, main.cpp can be compiled, but when I include node.h in main.cpp, I get errors!

      What should I do if I want to include node.h in main.cpp?

      • Tyler

        Where is the node.h file saved to? The compiler always looks for header files in the same directory as where the main.cpp is located.

        If this is not the problem, please post your full code and list of errors so that we can further assist you.

        -Tyler

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

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

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

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

  • hatam

    its very goooog…..i am irann

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

    why?

    thanks in advanced :)

  • Qazerowl

    Ok, I used the same code except O put in #include “stdafx.h” in all of the files, i get this error.

    —— Build started: Project: Learning, Configuration: Debug Win32 ——
    Learning.cpp
    Learning.obj : error LNK2019: unresolved external symbol “int __cdecl add(int,int)” (?add@@YAHHH@Z) referenced in function _main
    C:…visual studio 2010ProjectsLearningDebugLearning.exe : fatal error LNK1120: 1 unresolved externals
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

  • Andy

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

    here is main.cpp:

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

    —— Build started: Project: add, Configuration: Debug Win32 ——
    Compiling…
    main.cpp
    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?

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

  • Atul

    i copied the example from above tutorial and after compiling i get the error, example and error are written below

    add.h:

    #ifndef ADD_H
    #define ADD_H

    int add(int x, int y)

    #endif

    here is main.cpp:

    #include “stdafx.h”
    #include
    #include “add.h”

    int main()
    {
    using namespace std;
    cout << "The sum of 3 and 4 is: " << add(3, 4) <
    Here is the error
    —— Build started: Project: main, Configuration: Debug Win32 ——
    1>Compiling…
    1>main.cpp
    1>c:documents and settingsadministratormy documentsvisual studio 2005projectsmainmainmain.cpp(6) : fatal error C1083: Cannot open include file: ‘add.h': No such file or directory
    1>Build log was saved at “file://c:Documents and SettingsAdministratorMy DocumentsVisual Studio 2005ProjectsmainmainDebugBuildLog.htm”
    1>main – 1 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • PaperTiger87

      In your main.cpp, line 2 should’ve been #include
      also is the last line, ‘<' should be ';'.

      • Actually it’s a bug with this site – it for some reason does this to all code. When you see a lone #include it means that he’s including iostream. The extra ‘<' is probably there because he didn't copy the whole main file.

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

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

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

    main.cpp

    add.h

    add.cpp

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

    Thanks!

  • 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
    #include
    #include”stdio.h”

  • Jeff Johnson

    I’m getting this error

    Compiler: Default compiler
    Building Makefile: “C:\Dev-Cpp\Makefile.win”
    Executing make…
    make.exe -f “C:\Dev-Cpp\Makefile.win” 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

  • binod

    class algebra
    {

    public:
    int add(int ,int );

    }
    int algebra::add(int a,int b)
    {
    return (a+b);
    }

    #include
    #ifndef “algehra.h”
    #include “algebra.h”
    using namespace std;
    int main()
    {
    int a,b;
    cin>>a>>b;
    algebra aa;

    cout<<"addtioon=";
    aa.add(a,b);
    system("pause");
    return 0;
    }
    #endif

  • binod

    // grades.h
    #include
    using namespace std;

    class Grades
    {
    public:

    // function to prompt for 10 grades using while loop
    void getGrade()
    {
    int total = 0;
    int grade;
    int counter = 1;
    int average = total / 10;

    while ( counter <= 10 )
    {
    cout <> grade;
    if (( grade 100 ))
    cout << "Invalid scoren";
    else
    {
    total += grade;
    counter++;
    }
    }

    cout << "nThe average grade is: " << total / 10 << "n";
    }
    }; // end class

    #include
    #include “grades.h”
    using namespace std;

    int main()
    {
    Grades myGrades; // create an object of class Grades
    myGrades.getGrade(); // call the member function of object myGrades
    system(“pause”);
    return 0;
    }
    here I tried to link grades.h header files but shows link error so,i copied header file to include directory in dev cpp .then it worked,but it looks so weird, how to link without coping header file to include directory

  • binod

    here I tried to link grades.h header files but shows link error so,i copied header file to include directory in dev cpp .then it worked,but it looks so weird, how to link without coping header file to include directory

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

  • Shaun

    i was just messing around with the earlier program of

    i figured out i dont need another .cpp file containing add() that i can list my return value of add()within the header file add.h if this was already mentioned than i apologize, but i just thought id note this.

    great tutorial by the way, im loving it!

  • masud

    Thanks for this tutorial……….

  • baz

  • ccy

    “So if cout is only defined in the “iostream” header file ….”

    should be

    “So if cout is only declared in the “iostream” header file …”

  • 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

    and

    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

  • Leo

    Using VC++ 2010 Express, i get an error if in Add.cpp i don’t add:

    before the definition of the function.

  • auguster

    am using visual c++ 2010 and i figured the add.h file written in forum does’t work for me.This is how it worked for me:-
    #include “stdafx.h”

    #ifndef ADD_H
    #define ADD_H

    int add(int x,int y)//function prototype for add.h
    {
    return x+y;
    }
    #endif

  • jrnemo01

    I can’t include my header files in my cpp files!
    I use dev c++. Help please!

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

  • Tweak

    getting compile error “undefined reference to `add(int, int)'” despite doing everything exactly as in the tutorial.

    add.h:
    #ifndef ADD_H
    #define ADD_H

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

    #endif

    add.cpp:
    #include “add.h”
    int add(int x, int y)
    {
    return x + y;
    }

    main.cpp:
    #include
    #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;
    }

    any idea what could be wrong? using code::blocks
    tried with and without the "#include "add.h"" line in add.cpp

  • SWEngineer

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

  • pastry

    hi.
    I tried many times but header file is not working in dev-c++ , it showing error as add.h no such files or directory

    please help me out
    thnx :)

  • pastry

    I got the solution . in total 3 files one project and two source file main.cpp, add.cpp, add.h

  • eturnallife

    I see. If you are using visual c++ create two files in addition to your projects .cpp file, i.e. random.cpp, main.cpp and add.cpp. leaving the project .cpp file alone and working in main.cpp and add.cpp it will work.

  • thomasalva

    Try with g++. Using g++ in linux g++ (Ubuntu 4.4.1-4ubuntu9) 4.4.1
    main.cpp
    #include
    int add(int x, int y); // forward declaration using function prototype
    int main() {
    std::cout << "Sum of 3 and 4 is : " << add(3,4) << std::endl;
    return 0;
    }
    add.cpp
    int add(int x, int y)
    {
    return x + y;
    }
    Compile & link:
    CompaqCQ5210F:~/Ctest$ g++ main.cpp add.cpp -o main
    run:
    CompaqCQ5210F:~/Ctest$ ./main
    Sum of 3 and 4 is : 7

  • adamrv1

    “This way, older programs that include #include …”

    should be

  • adamrv1

    woops, html is enabled.

    iosteam should be iostream.

  • Jack

    Using Code :: Blocks and can’t get this or forward declarations to work. Yes Debug and Release are both checked, in fact it was the default. I noticed under properties compile and link were deselected in add but even when I tried enabling them got the error:

    /home/jack/CTutorials/Helloworld/main.cpp|2|fatal error: add.h: No such file or directory|
    ||=== Build finished: 1 errors, 0 warnings ===|

    This specific error was when trying the header file. Something like “add undefined” was my error in forward declarations. Can anybody help (programming in Linux-Ubuntu btw).

    • Jack

      Never mind, figured it out. It couldn’t find add.h because Code :: Blocks simply recognizes it as

      #include “add”

      but this alone won’t work unless you add a forward declaration for the functions in add you want to use, the final code for main.cpp should look like this:

      #include
      #include “add”

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

      Other than that that one issue this tutorial has been amazing so far. I've been reading it less than 24 hours (having no prior experience in C++ but some in Java) and have already managed to write 3 simple but useful programs with what I've picked up so far.

  • Lakshya

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

  • zamanengineer001

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

  • Pratik Patel

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

  • Agyetech

    I use Turbo c++ compiler which really accepts both types.
    is it really advisable to use any?

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

  • Da-Rage44

    I’m not sure if this is another noob statement I’m making but doesn’t having a add.cpp file with the predeclared function add() while creating a add.h file make this excersize redundant? It’s a stupid question but isn’t this what the excersize has us do?

  • Madeinqc

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

  • mm

    Hi
    I tried to use the add() function in a Class.
    But I got this error :
    error LNK2019: unresolved external symbol “public: int __thiscall Class1::add(int,int)” (?add@Class1@@QAEHHH@Z) referenced in function _main
    error LNK1120: 1 unresolved externals

    I am using Microsoft Visual Studio 2008. Created a win32 Console Application.

    I have put the 3 files below. Main.cpp Class1.cpp and Class1.h
    There seems to be a problem Linking but I can not figure out why.
    Thanks a lot for your help, greatly appreciate your help.

    FILE: MAIN.cpp_____________________________________________

    #include
    #include
    #include “Class1.h”
    int main()
    {
    Class1 c;
    int res=c.add(3, 4);
    return 0;
    }
    _____________________________________________
    FILE: Class1.cpp_____________________________________________
    #include

    class Class1
    {
    public:
    int add(int x, int y)
    {
    return x + y;
    }
    };

    _____________________________________________
    FILE:Class1.h_____________________________________________
    #ifndef CLASS1_H
    #define CLASS1_H

    class Class1
    {
    public:
    int add(int x, int y); // function prototype
    };

    #endif

    • nisbahmumtaz

      What I did was change the content of “add.h” by adding:

      {
      return x + y;
      }

      This way, I didn’t even need the add.cpp and it compiled just fine.
      I think this is a compatibility error on behalf of Alex, since this guide was made for C++03 originally.

    • pman2591

      Had the same issue with Visual Studio 2010…

  • Nitin

    amazing i find this website to be very helpful

  • The following source for
    main.cpp, add.cpp and add.h
    worked using Microsoft Visual C++ Express 2010

    I still don’t understand the first two lines in the add.h file.

    #ifndef MATH_H

    and

    #define MATH_H

    My first impression was “ifndef” was a typo of “define” with “MATH_H” being a derivative of “math.h”. Apparently I’m wrong since it does in fact work. I just don’t understand the where and how of those two lines substance.

    #define

    makes sense

    #ifndef

    I don’t understand. It looks like “define” scrambled.

    MATH_H

    I don’t understand. “math.h” would seem to make more sense. I surmise “MATH_H” is a Microsoft addon to the standard library though I would think that would require an include statement, not a define.

  • I see the next page, Section 1.10 has this to say:
    To prevent this from happening, we use header guards, which are conditional compilation directives that take the following form:

    #ifndef SOME_UNIQUE_NAME_HERE 
    #define SOME_UNIQUE_NAME_HERE   
    
    // your declarations here   
    
    #endif 
    

    SO, the “MATH_H” is merely some unique name to ensure the particular header file is not included more than once. I still don’t understand the

    #ifndef</PRE part though.
  • Deceit

    Ok I question first is the Header suppose to be made separate from the .cpp? or is the header suppose to be included inside the .cpp?

    I’m using Visual studio 2010

    ok this is what I’ve been trying to do. I first start making a header by going to File – New – File – Visual C++ – Header File C (.h)

    I input:

    #ifndef ADD_H
    #define ADD_H

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

    #endif

    After that I save it as ADD_H

    After that I make a new .Cpp (File – New – Win32 Console Applications)

    then I input:

    #include
    #include “stdafx.h”
    #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) <.<

    • Ashoenew

      I take it you had the same prob I had did you come up with a link error or did it run fine? you didn’t specify

      • Deceit

        Ok I understand wat I did wrong I didn’t the header file that I made into
        to .cpp file that i’m using it for
        BUT! everything said it was fine but… when I tried to complied with an fail… this is the error code

        1>—— Build started: Project: Lesson1.9, Configuration: Debug Win32 ——
        1> Lesson1.9.cpp
        1>c:\users\culex\documents\visual studio 2010\projects\lesson1.9\lesson1.9\add.h(5): error C2447: ‘{‘ : missing function header (old-style formal list?)
        ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

        P.S. I wrote more on my original but.. it cutted it off…

  • Ashoenew

    Ok so im using Microsoft visual c++ express 2010 and I followed the instructions completely and I came up with a link error.? so any help? here is what i have for add.h

    #ifndef ADD_H
    #define ADD_H

    int add(int x, int y);

    #endif

    // this is what i have for main.cpp

    #include “stdafx.h”
    #include
    #include “add.h”

    int main()
    {
    using namespace std;
    cout << "The sum of 3 and 4 is:" << add(3,4) <—— Build started: Project: add, Configuration: Debug Win32 ——
    1> add.cpp
    1>add.obj : error LNK2019: unresolved external symbol “int __cdecl add(int,int)” (?add@@YAHHH@Z) referenced in function _main
    1>C:\Users\\add\Debug\add.exe : fatal error LNK1120: 1 unresolved externals
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • Ashoenew

      i did finish the program it just didn’t post it all.

      • Ashoenew

        what did i do wrong or why did i get a link error? thanks in advance. also thanks for being patient.

        • Deceit

          Ok… this is how to make header files on Microsoft Visual 2010 and insert it into your other projects

          Part1: First of all you’ll have to create a header file first go to

          File –

          New –

          File –

          Visual C++ –

          Header File – (The file will be named by itself but I recommend you change it to the name you want by going to save as)[Also there is no need to add “.h” when naming it, it will be inserted by itself]{Also I named my “add” so i’ll be using my name for example}

          • Deceit

            Part 2

            Now to input the code
            Like this:

            #ifndef ADD_H
            #define ADD_H

            int add(int x, int y )
            {
            return x + y;
            }
            #endif

            After that save and close project

            Part 3 Your Project

            Insert the code:

            // Lesson1.9.cpp : Defines the entry point for the console application.
            //

            #include “stdafx.h”
            #include
            #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;
            }

            Save it and close

          • Deceit

            Part 4

            Now I suggest you start making a header folder for you header files

            Now find your header file and then copy

            After that find your project you just saved
            {Good chance it will be where mine is}[Documents-Visual Studio 2010-Projects]

            After that enter your project and go to “Name of your project”
            For example my project was named “Lesson 1.9″
            {Projects- Lesson 1.9 – {When you see other head files insert it in there}

            Ok now open your “Project” and on the right of screen there should be “Solution Screen” and under Headers add your header

            AND BAM your done try running it if it doesn’t work all hope is lost for you.. I guess. Well I got mine to work :)

          • Ashoenew

            That worked perfectly thanks!!!

  • sanusha

    #include
    #include
    #include “Dll.h”
    #include “guid.h”
    can u say the meaning of these header files

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

  • 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

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

      .h
      #ifndef ADD_H_INCLUDED
      #define ADD_H_INCLUDED

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

      #endif // ADD_H_INCLUDED

      main.cpp

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

  • 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:
    http://en.wikipedia.org/wiki/Precompiled_header#stdafx.h

  • ashik

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

  • xconwing

    Yea, having a compile error as well. This is what I have in all three file.

    in main.cpp
    ////////////////////////
    #include
    #include “add.h” // this brings in the declaration for add()
    using namespace std;

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

    in add.cpp
    ////////////////////////
    #include "add.h"

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

    in add.h
    ////////////////////////
    #ifndef ADD_H
    #define ADD_H

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

    #endif

    Btw, I’m working with CodeBlock compiler and the error is:
    undefined reference to ‘add(int, int)’

    thanks
    qL

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

  • roy17

    hi
    i been trying to create a .h file and .cpp file
    i was able to use these two file as the header in the same project where i have saved both .cpp and .h file
    but i was not able to use in the different project
    it shows a message “file not found”
    by the way i am using Xcode

    when i use
    # include
    # include “GradeBook.h”
    using namespace std;
    int main ()
    {
    GradeBook gradeBook(“CS101 Introduction to C++ Programming”);
    GradeBook gradeBook1(“CS102 Introduction to C++ Programming”);
    cout<< "gradeBook created for course:"<<gradeBook.getCourseName()<<"\n gradeBook1 creaded for course:"<<gradeBook1.getCourseName()<<endl;

    return 0;

    }

    in the same project where i have .h file

    #ifndef practice_of_the_header_GradeBook_h
    #define practice_of_the_header_GradeBook_h
    # include

    using namespace std;

    class GradeBook
    {
    public:
    // provide all the member function protype
    GradeBook (string);// this is a consturctor
    void setCourseName(string);
    string getCourseName();
    void displayMessage();

    private:
    string CourseName;

    };// the class of the Gra

    #endif

    and .cpp flie

    # include
    # include
    #include “GradeBook.h”
    using namespace std;
    // constructor initialixes course Name with string supplies as argument
    GradeBook::GradeBook(string name)
    {
    setCourseName(name);

    }
    // function to set the course name
    void GradeBook::setCourseName(string name)
    {
    CourseName=name;
    }
    string GradeBook:: getCourseName()
    {
    return CourseName;

    }
    void GradeBook::displayMessage()
    {
    cout<<"Welcome to the grade book \n"<<getCourseName()<<"!"<<endl;
    }

    i worked fine

    but when i created a new project
    and try to use the same header it says file not found

    # include
    # include “GradeBook.h” !GradeBook.h file not found
    using namespace std;
    int main ()
    {
    GradeBook gradeBook(“CS101 Introduction to C++ Programming”);
    GradeBook gradeBook1(“CS102 Introduction to C++ Programming”); cout<< "gradeBook created for course:"<<gradeBook.getCourseName()<<"\n gradeBook1 creaded for course:"<<gradeBook1.getCourseName()<<endl;

    return 0;

    }

    can any one help me
    thanks

  • 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

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

  • fantastic source code!hi every body!

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

  • TheElephant

    Keep in mind that header files typically only contain declarations. They do not define how something is implemented, and you already know that your program won’t link if it can’t find the implementation of something you use.

    #include
    #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;
    }
    int add(int x, int y)
    {
    return x + y;
    }
    int add(int x, int y)
    {
    return x + y;
    }

  • TheElephant

    Keep in mind that header files typically only contain declarations. They do not define how something is implemented, and you already know that your program won’t link if it can’t find the implementation of something you use.

    #include
    #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;
    }

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

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

  • Ciprian

    Just AMAZING, this tutorial . .

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

    Cheers!

  • The sentence “So if cout is only defined in the “iostream” header file, where is it actually implemented?” I think it should be “So if cout is only declared in the “iostream” header file, where is it actually implemented (defined)?” Correct me if I am wrong. Thanks.

  • Alam

    i get the following error:
    Error 1 error C1083: Cannot open include file: ‘add.h': No such file or directory

    Why i get this error?
    can any one explain pls
    i wrote it as such:

    ifndef ADD_H
    #define ADD_H

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

    #endif

    #include
    #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;
    }

    Error 1 error C1083: Cannot open include file: 'add.h': No such file or directory

    Why i get this error?
    can any one explain pls

Leave a Comment (Note: put C++ code inside [code][/code] brackets)

  

  

  

1 × five =

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">