Code files (with a .cpp extension) are not the only files commonly seen in programs. The other type of file is called a header file, sometimes known as an include file. Header files almost always have a .h 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:
#include <iostream>
int main()
{
using namespace std;
cout << "Hello, world!" << endl;
return 0;
}
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:
int add(int x, int y)
{
return x + y;
}
main.cpp:
#include <iostream>
int add(int x, int y); // forward declaration using function prototype
int main()
{
using namespace std;
cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
return 0;
}
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:
#ifndef ADD_H #define ADD_H int add(int x, int y); // function prototype for add.h #endif
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:
#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;
}
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
|
1.10 — A first look at the preprocessor
Index
1.8 — Programs with multiple files
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.
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
its very goooog…..i am irann
its nike too meeky us ;d
(crippled in english)
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 :)
wonderful tutorials!
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 ==========
nevermind, i didn’t include the files in the project…
i am making multiple files copying what the tutorials say, and here is the code i have input:
add.h:
here is main.cpp:
#include "stdafx.h" #include <iostream> #include "add.h" int main() { using namespace std; cout << "The sum of 3 and 4 is: " << add(3, 4) << endl; return 0; }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?
In “add.h” add a semicolon at the end of the function declaration:
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!
nevermind, I guess headers are not supposed to be linked. Hope somebody some day reads these and it helps them out at least.
[...] 1.9 Header files [...]
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 ==========
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.
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.
Ya, but when you have 9 or 10 different forward declarations for your program….
It makes it neater to have it all together
[...] http://www.learncpp.com/cpp-tutorial/19-header-files/ [...]
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:
#ifndef ADD_H #define ADD_H int add(int x, int y) // function prototype for add.h { return x + y; // without this the function doesn't know what you want it to do } #endifReason for the change…a function must be declared in order to work.
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!
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+0×128): In function `main’:
: undefined reference to `add(int, int)’
collect2: ld returned 1 exit status
This is my code –
main.cpp
#include <iostream> #include "add.h" int main() { std::cout << "Sum of 3 and 4 is : " << add(3,4) << std::endl; }add.h
add.cpp
#include "add.h" int add(int a, int b) { return (a + b); }This is the version of my c++ compiler –
gcc version 3.4.6 20060404 (Red Hat 3.4.6-9)
Thanks!
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”
[...] used it before, and I wanted to create a project like this main.cpp add.h Here is the example. Learn C++ – I created a project, added add.h and main.cpp I am sure if I was doing it right: I do build but [...]
ADD.h #ifndef ADD_H #define ADD_H int add(int x, int y); // function prototype for add.h #endif ADD.cpp #include <iostream> int add(int x, int y) { return x + y; } main.cpp #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; cin.clear(); cin.ignore(255, '\n'); cin.get(); return 0; }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+0×100):ADD.cpp: multiple definition of `add(int, int)’
main.o(.text+0×100):main.cpp: first defined here
collect2: ld returned 1 exit status
make.exe: *** [Project1.exe] Error 1
Execution terminated
I’m using bloodshed
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
// 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
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.
i was just messing around with the earlier program of
#include "stdafx.h" #include <iostream> #include "Add.h" int main() { using namespace std; cout << "The sum of 3 and 4 is: " << add(3, 4) << endl; return 0; }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!
Thanks for this tutorial……….
“So if cout is only defined in the “iostream” header file ….”
should be
“So if cout is only declared in the “iostream” header file …”
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
Using VC++ 2010 Express, i get an error if in Add.cpp i don’t add:
before the definition of the function.
yes,it’s right.
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
I can’t include my header files in my cpp files!
I use dev c++. Help please!
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?
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
Excellent tutorial, explained in a simple manner. Thanks a lot.
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 :)
I got the solution . in total 3 files one project and two source file main.cpp, add.cpp, add.h
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.
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
“This way, older programs that include #include …”
should be
woops, html is enabled.
iosteam should be iostream.
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).
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.
Tried a lot but got errors. Finally figured my header file name was not add.h but something else. Phew!
what is functionality of these lines in add.h file:
#ifndef ADD_H
#define ADD_H
#endif
[...] Header Files 63.410428 10.446349 [...]
In header add.h, add() is not defined, that’s why many of you are having an error…
I use Turbo c++ compiler which really accepts both types.
is it really advisable to use any?
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?
Create a new project, uncheck “use precompiled header”, OR reinstall Visual Studio (get 2010 at once!).
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?
This was way more clear than college, helped me out a lot.
[...] Thanks. Have been reading the cplusplus.com tutorial. Think there are a few other ones also. This is also a good one. http://www.learncpp.com/cpp-tutorial/19-header-files/ [...]