C++ Header and Source Files

Introduction

We can split our C++ code into multiple files.

By convention, there are two kinds of files into which we can store our C++ source: header files (headers) and source files.

Header files are source code files where we usually put various declarations.

Header files usually have the .h (or .hpp) extension.

Source files are files where we can store our definitions and the main program.

They usually have the .cpp (or .cc) extension.

Then we include the header files into our source files using the #include preprocessor directive.

To include a standard library header, we use the #include statement followed by a header name without an extension, enclosed in angle brackets <header_name>.

Example:

#include <iostream> 
#include <string> 
// etc 

To include user-defined header files, we use the #include statement, followed by a full header name with extension enclosed in double-quotes. Example:

#include "myheader.h" 
#include "otherheader.h" 
// etc 

The realistic scenario is that sometimes we need to include both standard-library headers and user-defined headers:

#include <iostream> 
#include "myheader.h" 
// etc 

The compiler stitches the code from the header file and the source file together and produces what is called a translation unit.

The compiler then uses this file to create an object file.

A linker then links object files together to create a program.

We should put the declarations and constants into header files and put definitions and executable code in source files.




PreviousNext

Related