Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What is in a header file?A whole definition of a function?

Status
Not open for further replies.

newbie1

Technical User
Sep 17, 2002
4
US
I´m a newbie and this I don´t understand.The compilation is done in two steps.If we have,lets say #include directive in a source file,then preprocessor phase adds the contents of a header file to a .CPP file.My question is:
-Does a header file contain the whole definition of some function?If so,why then linker links file to a library functions,afterall,header code has been already included in file at preprocessor phase.I´m hoping for someone to clarify me this.
I appreciate your help a lot!!!

 
You could place a function entirely within a header file, i.e. both it's definition and it's body. This is not normally done however because if you require to include the header file in more than 1 of your source (.cpp) file you would get "function already defined" errors.
Put simply, the purpose of a header file is to allow functions held in one cpp file to access functions (amongst other things) defined in another.
In C you can call a function without defining a prototype beforehand, in C++ this is not allowed.

In other words;
if within your .cpp file you have
int a = xyz('W');

you must have somewhere before the call to the xyz the following;
int xyz(char c);

this 'prototype' of the function would normally be held in a header file that in turn is included in any .cpp files where the function is required.
 
A header file SHOULD be used to define the interface for a body of code. In C++, this is usually a class definition. There are a few exceptions based on compilers and such - for example, template functions have to have full definitions in the header file (at least in VC++ 6.0 - newer compilers might be able to get around this). The linker is used to link the object code created by the compiler (from your source code, as well as library files) into a file that the OS knows how to execute. So even if you're program is completely self-contained, you will still need the linker to make your executable.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top