Navigation

Search

Meta

1.9 — Header files

By Alex, on June 3rd, 2007

Headers, and their purpose

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

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

Using standard library header files

Consider the following program:

1

2

3

4

5

6

7

#include <iostream>

intmain()

{

usingnamespacestd;

cout<<"Hello, world!"<<endl;

return0;

}

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

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

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

Writing your own header files

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

add.cpp:

1

2

3

4

intadd(intx,inty)

{

returnx+y;

}

main.cpp:

1

2

3

4

5

6

7

8

9

10

#include <iostream>

intadd(intx,inty);// forward declaration using function prototype

intmain()

{

usingnamespacestd;

cout<<"The sum of 3 and 4 is "<<add(3,4)<<endl;

return0;

}

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

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

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

add.h:

1

2

3

4

5

6

7

8

9

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

#ifndef ADD_H

#define ADD_H

// This is the content of the .h file, which is where the declarations go

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

Consequently, our program will compile and link correctly.

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

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

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

Angled brackets vs quotes

You’re probably curious why we use angled brackets for iostream, and double quotes for add.h. The answer is that angled brackets are used to tell the compiler that we are including a header file that was included with the compiler, so it should look for that header file in the system directories. The double-quotes tell the compiler that this is a header file we are supplying, so it should look for that header file in the current directory containing our source code first. If it doesn’t find the header file there, it will check any other include paths that you’ve specified as part of your compiler/IDE settings. That failing, it will fall back to checking the system directories.

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

Why doesn’t iostream have a .h extension?

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

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

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

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

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, you should give them all a .h extension, since you will not be putting your code in the std namespace.

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

Including header files from other directories

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

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

1

2

#include "headers/myHeader.h"

#include "../moreHeaders/myOtherHeader.h"

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

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

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

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

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

1

g++-omain-I/source/includes main.cpp

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

Can I put function definitions in a header file?

C++ won’t complain if you do, but generally speaking, you shouldn’t.

As noted above, when you #include a file, the entire content of the included file is inserted at the point of inclusion. This means that any definitions you put in your header get copied into every file that includes that header.

For small projects, this isn’t likely to be much of an issue. But for larger projects, this can make things take much longer to compile (as the same code gets recompiled each time it is encountered) and could significantly bloat the size of your executable. If you make a change to a definition in a code file, only that .cpp file needs to be recompiled. If you make a change to a definition in a header file, every code file that includes the header needs to be recompiled. One small change can cause you to have to recompile your entire project!

Sometimes exceptions are made for trivial functions that are unlikely to change (e.g. where the function definition is one line).

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.

Each header file should have a specific job, and be as independent as possible. For example, you might put all your declarations related to functionality A in A.h and all your declarations related to functionality B in B.h. That way if you only care about A later, you can just include A.h and not get any of the stuff related to B.

Give your header files the same name as the source files they’re associated with (e.g. grades.h goes with grades.cpp).

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

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.

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

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

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?

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.

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

I had the same problem till I realised that of course files are saved to the last place used so VS was saving to the mutli file project from the prior lesson. moved the .h file to the folder for this project and its ok

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.

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.

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?

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:

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

#include <iostream>

#include "ADD.h"

intmain()

{

cout<<"enter a number: ";

intx;

cin>>x;

cout<<"you entered "<<x<<" enter a number to add to this: "

inty;

cin>>y;

cout<<"the sum of these two numers is "<<add(x,y)<<endl;

system("puase")

return0;

}<!--formatted-->

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.

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.

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.

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.

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

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

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

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

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

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.

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.

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.

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.

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.

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.

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?

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

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

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

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

1

2

3

4

5

6

7

8

9

10

11

#include <iostream>

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

intadd(intx,inty);

intmain()

{

usingnamespacestd;

cout<<"The sum of 3 and 4 is "<<add(3,4)<<endl;

return0;

}

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

but when I change to this

1

2

3

4

5

6

7

8

9

10

11

#include <iostream>

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

intadd(intx,inty);

intmain()

{

usingnamespacestd;

cout<<"The sum of 3 and 4 is "<<ADD_H(3,4)<<endl;

return0;

}

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?

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?

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:

1

g++main.cpp add.cpp add.h-oadd.o

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.

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’

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!

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.

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!

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

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

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.

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

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

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

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

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?

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?

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.

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.

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.

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

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

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?

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!

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.

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.

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

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

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