Skip to main content

Header files and libraries

A header file is a file usually ending (always in C but not necessarily in C++) with the “.h” extension that can be included in the source code of a program with the preprocessor directive include followed by the name of the file between angular brackets or quotation marks:

#include <filename>
#include <filename.h>
// or
#include "filename"
#include "filename.h"

There are two types of header files:

  1. Pre-existing header files
  2. User-defined header files

An example of a header file is the built-in iostream standard library header (full list), which contains the declarations related to objects like cin and cout used for manipulating I/O streams, as we saw in the Cout/Cin lesson.

Content and differences

caution

The following part is about an advanced topic. If you don't already know functions and classes feel free to skip these paragraphs.

Following the standard, a header file contains predefined function declarations (also called function prototypes), macros definitions and classes (but also data types and constants used with the libraries) to be shared between several source files but cannot contain function definitions, which are instead contained in the libraries (or multiple .c/.cpp source files which are compiled in object code .o and then packed into a library .lib, eventually composed by multiple .o files).

Libraries are a compiled set of function definitions (the actual implementations of instructions) of the declarations in the header files consisting of many 0 and 1, not source code like header files do. The library is included in your .exe file at link time.

The reasons why function definitions should not be written inside header files are explained here, here and here. If you are confusing header files with libraries, see this GeeksforGeeks comparison article.

Lastly, I also suggest a great in-deep lesson by Learn C++ all about header files.