3.1.2 Header File

Libraries are typically imported through a header file. By convention, header files typically have a file extension of .h and are the main connection users have to a library.

Creating a Header File Library

Creating a library in a header function is as simple as creating any other code in your program. When the file is imported into your program, the code from your header file is essentially written into your main program at the import statement. When you write functions in your header file, you have access to these functions as if they were in your program.

Since your header file may be imported before other import statements, it is important to include imports in your header file that would be necessary for the code in your header file. For example, if you have a function in the header file that reads from the console, you need to include the iostream library in the header file.

Using a Header File Library

Importing a header file library and using it is very similar to how you import a standard C++ library such as vectors or iostream. The biggest difference is that the library name is enclosed in quotes.

For example, if you had a random number library with a header file called random.h, any program that wanted to use the library would use this include statement:

#include "random.h"

Once imported, you can then call a function as if it was in your program.

Example

In this example, you can see that the input.h file creates a basic function to read a line of text based on a prompt input. This can be a handy function since it allows the user to read in from a user in a single line.

One thing to notice is that both the input.h and the main file import iostream. C++ manages the double import in a safe way, so it is not an issue. You will see more about this in an upcoming example.

Note: To see multiple files, select the file tab on the right column next to your code.

Last updated