16
« 1.8 — Programs with multiple files 1.10 — A first look at the preprocessor » 1.9 — Header files BY ALEX, ON JUNE 3RD, 2007 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: 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 1 2 3 4 5 6 7 #include <iostream> int main() { using namespace std; cout << "Hello, world!" << endl; return 0; } 1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/ 1 of 16 04/07/13 13:13

c++ Header Files

Embed Size (px)

DESCRIPTION

Header Files Tutorial C++

Citation preview

Page 1: c++ Header Files

« 1.8 — Programs with multiple files 1.10 — A first look at the preprocessor »

1.9 — Header filesBY ALEX, ON JUNE 3RD, 2007

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:

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

1234567

#include <iostream>int main(){ using namespace std; cout << "Hello, world!" << endl; return 0;}

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

1 of 16 04/07/13 13:13

Page 2: c++ Header Files

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:

1234

int add(int x, int y){

return x + y;}

123456789

10

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

}

123456

#ifndef ADD_H#define ADD_H

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

#endif

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

2 of 16 04/07/13 13:13

Page 3: c++ Header Files

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!

123456789

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

}

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

3 of 16 04/07/13 13:13

Page 4: c++ Header Files

« 1.8 — Programs with multiple files 1.10 — A first look at the preprocessor »

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

C++ TUTORIAL | PRINT THIS POST

191 comments to 1.9 — Header files

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

4 of 16 04/07/13 13:13

Page 5: c++ Header Files

« Older Comments 1 2 3

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

5 of 16 04/07/13 13:13

Page 6: c++ Header Files

mmDecember 8, 2011 at 7:55 am Log in to Reply

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

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

6 of 16 04/07/13 13:13

Page 7: c++ Header Files

nisbahmumtazJanuary 6, 2012 at 4:37 am Log in to Reply

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.

Programs with multiple files | 4sharesiteDecember 18, 2011 at 5:08 am Log in to Reply

[...] Now, when the compiler is compiling main.cpp, it will know what add is. Using this method, we can give

files access to functions that live in another file. However, as programs grow larger and larger, it becomes

tedious to have to forward declare every function you use that lives in a different file. To solve that problem,

the concept of header files was introduced. We discuss header files in the lesson on header files. [...]

1.8 — Programs with multiple files « kickasscomputingDecember 23, 2011 at 12:21 am Log in to Reply

[...] Now, when the compiler is compiling main.cpp, it will know what add is. Using this method, we can give

files access to functions that live in another file. However, as programs grow larger and larger, it becomes

tedious to have to forward declare every function you use that lives in a different file. To solve that problem,

the concept of header files was introduced. We discuss header files in the lesson on header files. [...]

NitinJanuary 1, 2012 at 11:38 pm Log in to Reply

amazing i find this website to be very helpful

Wayne WilhelmJanuary 20, 2012 at 4:47 pm Log in to Reply

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

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

7 of 16 04/07/13 13:13

Page 8: c++ Header Files

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.

Wayne WilhelmJanuary 20, 2012 at 5:14 pm Log in to Reply

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.

Wayne WilhelmJanuary 20, 2012 at 11:16 pm Log in to Reply

I now understand. The next page we go to (1.10) explained the

#ifndef

term. Essentially the entire header file is an IF statment. Because the term MATH_H has to be unique,

we ask

#ifndef

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

8 of 16 04/07/13 13:13

Page 9: c++ Header Files

if not defined then perform all of the statements after until the next

#endif

end of if statment.

Wayne WilhelmJanuary 20, 2012 at 11:18 pm Log in to Reply

Guess I need to quit posting and just read on. All will be explained in good time…

Sorry!

DeceitFebruary 5, 2012 at 10:36 pm Log in to Reply

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

AshoenewFebruary 7, 2012 at 4:30 am Log in to Reply

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

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

9 of 16 04/07/13 13:13

Page 10: c++ Header Files

DeceitFebruary 7, 2012 at 4:26 pm Log in to Reply

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…

DeceitFebruary 7, 2012 at 4:56 pm Log in to Reply

Wooooo!!!! I understand what I did wrong and was able to compile it correctly

^^

AshoenewFebruary 7, 2012 at 4:23 am Log in to Reply

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

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

10 of 16 04/07/13 13:13

Page 11: c++ Header Files

February 7, 2012 at 4:25 am Log in to Reply

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

AshoenewFebruary 7, 2012 at 4:27 am Log in to Reply

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

being patient.

DeceitFebruary 7, 2012 at 5:43 pm Log in to Reply

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}

DeceitFebruary 7, 2012 at 5:48 pm Log in to Reply

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.

//

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

11 of 16 04/07/13 13:13

Page 12: c++ Header Files

#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

DeceitFebruary 7, 2012 at 6:32 pm Log in to Reply

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

AshoenewFebruary 8, 2012 at 12:10 am Log in to Reply

That worked perfectly thanks!!!

Class – A Simple Calculator Implementation Using A Class, Enum List, Typedef & Header

Files | My Programming NotesFebruary 11, 2012 at 8:07 pm Log in to Reply

[...] KNOWLEDGE FOR THIS PROGRAM Header Files – How To Use Them Class – Data Structure

Enumerated List Typedef Do/While Loop Passing a Value By Reference Constant [...]

sanushaFebruary 26, 2012 at 2:31 am Log in to Reply

#include

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

12 of 16 04/07/13 13:13

Page 13: c++ Header Files

#include

#include “Dll.h”

#include “guid.h”

can u say the meaning of these header files

C++ Help?March 30, 2012 at 7:45 pm Log in to Reply

[...] [...]

C++ || Class – Roman Numeral To Integer & Integer To Roman Numeral Conversion | My

Programming NotesApril 10, 2012 at 7:33 pm Log in to Reply

[...] KNOWLEDGE FOR THIS PROGRAM Header Files – How To Use Them Class – What Is It? Do/While

Loop Passing a Value By Reference Roman Numerals – How Do You Convert [...]

C++ || Class & Input/Output – Display The Contents Of A User Specified Text File To The

Screen | My Programming NotesApril 24, 2012 at 11:54 am Log in to Reply

[...] KNOWLEDGE FOR THIS PROGRAM Header Files – How To Use Them Class – What Is It? How To

Read Data From A File String – Getline Array – Cin.Getline Strcpy – Copy [...]

yuvadiusJuly 4, 2012 at 3:23 pm Log in to Reply

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

artxworksJuly 10, 2012 at 10:48 pm Log in to Reply

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

Tutorial: OOP in C++ (Part 2 – Class and object) « Learntofish's BlogOctober 6, 2012 at 8:51 am Log in to Reply

[...] – Line 01, 02 and 22 are part of the so-called “include guard”. When C++ includes this header file the first

time the name PERSON_H is assigned to it. If you try to include this header file a second time, which would

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

13 of 16 04/07/13 13:13

Page 14: c++ Header Files

result in an error, C++ checks if the name PERSON_H already exists. Since PERSON_H already exists from

the first include, the header file is not included again which prevents an error. – More on the include guard

can be found here: learncpp [...]

C++ Tutorials | 1.8 — Programs with multiple filesDecember 10, 2012 at 4:33 am Log in to Reply

[...] Now, when the compiler is compiling main.cpp, it will know what add is. Using this method, we can give

files access to functions that live in another file. However, as programs grow larger and larger, it becomes

tedious to have to forward declare every function you use that lives in a different file. To solve that problem,

the concept of header files was introduced. We discuss header files in the lesson on header files. [...]

C++ Tutorials 8.9 — Class code and header files | C++ TutorialsJanuary 26, 2013 at 5:47 am Log in to Reply

[...] the lesson on header files, you learned that you can put functions inside header files in order to reuse

them in multiple [...]

gu_obosFebruary 23, 2013 at 6:06 pm Log in to Reply

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

C++ for beginners, part 8a (finishing the project) | herclesMarch 13, 2013 at 9:36 am Log in to Reply

[...] this does yet, but just have faith and keep compiling’. It’s tricky to explain, but more info here if [...]

"undefined reference" error in a very very simple c++ program | BlogoSferaApril 3, 2013 at 7:49 pm Log in to Reply

[...] have a simple program, which I copied exactly from the example in http://www.learncpp.com

/cpp-tutorial/19-header-files/ because I’m learning how to make c++ programs with multiple [...]

ashikApril 29, 2013 at 9:01 am Log in to Reply

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

to me

ashikApril 29, 2013 at 11:26 am Log in to Reply

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

14 of 16 04/07/13 13:13

Page 15: c++ Header Files

the definition*

xconwingMay 22, 2013 at 7:22 pm Log in to Reply

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

Include header files in c++ | BlogoSferaJune 13, 2013 at 7:46 am Log in to Reply

[...] The C++ Premier I have doesn’t say much about what I am about to ask, and this is what I got googling

LINK: [...]

« Older Comments 1 2 3

You must be logged in to post a comment.

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

15 of 16 04/07/13 13:13

Page 16: c++ Header Files

« 1.8 — Programs with multiple files 1.10 — A first look at the preprocessor »

1.9 — Header files « Learn C++ http://www.learncpp.com/cpp-tutorial/19-header-files/

16 of 16 04/07/13 13:13