- Header files in C/C++ with Examples
- Header files (C++)
- Example
- Include guards
- What to put in a header file
- Sample header file
- Feedback
- C++ Header Files: A Pillar of Efficient Coding
- Why Do You Use Header Files?
- Basics to Advanced — Learn It All!
- What Are C++ Header Files?
- Types of Header Files
- Learn 15+ In-Demand Tools and Skills!
- How Do Header Files Work?
- How to Create a Header File in C++?
- Conclusion
- Find our Full Stack Java Developer Online Bootcamp in top cities:
- About the Author
Header files in C/C++ with Examples
C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the “.h” extension but in C, all the header files must necessarily end with the “.h” extension.
A header file contains:
It offer above features by importing them into the program with the help of a preprocessor directive “#include”. These preprocessor directives are used for instructing compiler that these files need to be processed before compilation.
In C program should necessarily contain the header file which stands for standard input and output used to take input with the help of scanf() and printf() function respectively.
In C++ program has the header file which stands for input and output stream used to take input with the help of “cin” and “cout” respectively.
There are of 2 types of header file:
- Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them.
- User-defined header files: These files are defined by the user and can be imported using “#include”.
#include or #include "filename.h"
We can include header files in our program by using one of the above two syntax whether it is pre-defined or user-defined header file. The “#include” preprocessor is responsible for directing the compiler that the header file needs to be processed before compilation and includes all the necessary data type and function definitions.
Note: We can’t include the same header file twice in any program.
Create your own Header File:
Instead of writing a large and complex code, we can create your own header files and include them in our program to use it whenever we want. It enhances code functionality and readability. Below are the steps to create our own header file:
- Write your own C/C++ code and save that file with “.h” extension. Below is the illustration of header file:
Header files (C++)
The names of program elements such as variables, functions, classes, and so on must be declared before they can be used. For example, you can’t just write x = 42 without first declaring ‘x’.
int x; // declaration x = 42; // use x
The declaration tells the compiler whether the element is an int , a double , a function, a class or some other thing. Furthermore, each name must be declared (directly or indirectly) in every .cpp file in which it is used. When you compile a program, each .cpp file is compiled independently into a compilation unit. The compiler has no knowledge of what names are declared in other compilation units. That means that if you define a class or function or global variable, you must provide a declaration of that thing in each additional .cpp file that uses it. Each declaration of that thing must be exactly identical in all files. A slight inconsistency will cause errors, or unintended behavior, when the linker attempts to merge all the compilation units into a single program.
To minimize the potential for errors, C++ has adopted the convention of using header files to contain declarations. You make the declarations in a header file, then use the #include directive in every .cpp file or other header file that requires that declaration. The #include directive inserts a copy of the header file directly into the .cpp file prior to compilation.
In Visual Studio 2019, the C++20 modules feature is introduced as an improvement and eventual replacement for header files. For more information, see Overview of modules in C++.
Example
The following example shows a common way to declare a class and then use it in a different source file. We’ll start with the header file, my_class.h . It contains a class definition, but note that the definition is incomplete; the member function do_something is not defined:
Next, create an implementation file (typically with a .cpp or similar extension). We’ll call the file my_class.cpp and provide a definition for the member declaration. We add an #include directive for «my_class.h» file in order to have the my_class declaration inserted at this point in the .cpp file, and we include to pull in the declaration for std::cout . Note that quotes are used for header files in the same directory as the source file, and angle brackets are used for standard library headers. Also, many standard library headers do not have .h or any other file extension.
In the implementation file, we can optionally use a using statement to avoid having to qualify every mention of «my_class» or «cout» with «N::» or «std::». Don’t put using statements in your header files!
// my_class.cpp #include "my_class.h" // header in local directory #include // header in standard library using namespace N; using namespace std; void my_class::do_something()
Now we can use my_class in another .cpp file. We #include the header file so that the compiler pulls in the declaration. All the compiler needs to know is that my_class is a class that has a public member function called do_something() .
// my_program.cpp #include "my_class.h" using namespace N; int main()
After the compiler finishes compiling each .cpp file into .obj files, it passes the .obj files to the linker. When the linker merges the object files it finds exactly one definition for my_class; it is in the .obj file produced for my_class.cpp, and the build succeeds.
Include guards
Typically, header files have an include guard or a #pragma once directive to ensure that they are not inserted multiple times into a single .cpp file.
// my_class.h #ifndef MY_CLASS_H // include guard #define MY_CLASS_H namespace N < class my_class < public: void do_something(); >; > #endif /* MY_CLASS_H */
What to put in a header file
Because a header file might potentially be included by multiple files, it cannot contain definitions that might produce multiple definitions of the same name. The following are not allowed, or are considered very bad practice:
- built-in type definitions at namespace or global scope
- non-inline function definitions
- non-const variable definitions
- aggregate definitions
- unnamed namespaces
- using directives
Use of the using directive will not necessarily cause an error, but can potentially cause a problem because it brings the namespace into scope in every .cpp file that directly or indirectly includes that header.
Sample header file
The following example shows the various kinds of declarations and definitions that are allowed in a header file:
// sample.h #pragma once #include // #include directive #include namespace N // namespace declaration < inline namespace P < //. >enum class colors : short < red, blue, purple, azure >; const double PI = 3.14; // const and constexpr definitions constexpr int MeaningOfLife< 42 >; constexpr int get_meaning() < static_assert(MeaningOfLife == 42, "unexpected!"); // static_assert return MeaningOfLife; >using vstr = std::vector; // type alias extern double d; // extern variable #define LOG // macro definition #ifdef LOG // conditional compilation directive void print_to_log(); #endif class my_class // regular class definition, < // but no non-inline function definitions friend class other_class; public: void do_something(); // definition in my_class.cpp inline void put_value(int i) < vals.push_back(i); >// inline OK private: vstr vals; int i; >; struct RGB < short r< 0 >; // member initialization short g< 0 >; short b< 0 >; >; template // template definition class value_store < public: value_store() = default; void write_value(T val) < //. function definition OK in template >private: std::vector vals; >; template // template declaration class value_widget; >
Feedback
Submit and view feedback for
C++ Header Files: A Pillar of Efficient Coding
Different languages have various predefined functions which help in writing and managing a program. Similarly, in C++, various header files play an essential part in C++ programming, and it helps to facilitate users by providing features to them while programming.
This tutorial on C++ Header files will help you learn all about Header files.
Why Do You Use Header Files?
Header files are used in C++ so that you don’t have to write the code for every single thing. It helps to reduce the complexity and number of lines of code. It also gives you the benefit of reusing the functions that are declared in header files to different .cpp files and including a header file is way easier than writing the implementations. By using a header file, you keep the program precise and focused, which makes it manageable.
Basics to Advanced — Learn It All!
What Are C++ Header Files?
These are those files that store predefined functions. It contains definitions of functions that you can include or import using a preprocessor directive #include. This preprocessor directive tells the compiler that the header file needs to be processed prior to the compilation. For example, the header file in C++ contains the definition of input-output functions.
Here, iomanip is the name of the header file, and .h is the extension of the header file. Unlike C, C++ header files may or may not have .h extension. It must enclose the name of the header file in the angle brackets, and #include is the preprocessor directive.
Here, the name of the header file is enclosed in double quotes, and this syntax is usually preferred when you are defining a user-defined header file.
And now, you will look at the types of header files.
Types of Header Files
Standard library header files: These are those header files that are already present in the compiler of C++; you just need to import them to use them.
User-defined header files: These are those header files defined by the user and can be used by including them in the program using #include.
Now, understand how these header files work.
Learn 15+ In-Demand Tools and Skills!
How Do Header Files Work?
When you include a header file, suppose #include in the program, it provides information to the compiler that it possesses this function and its functionality, and the compiler directly replaces the with its actual functionality or its content. Thus, you don’t have to write the code for it because you have already imported the header file, and it has all the information that the compiler needs to know.
How to Create a Header File in C++?
In C++, the code gets bigger and bigger with the functionality, and if you are working on some project, it would not be easy to manage and analyze the complete code of the project. So to avoid this problem, you can create your header file, and can use it whenever you require.
First of all, create a header file, and for that, you will write your code in the file, and save it with the .h extension, for example, fname.h. Here, you are using the .h extension because you are naming a header file.
The above code is of the header file fname.h
Now open a new file and write the code; for example, here, you have written the code to find the average of three numbers, but you haven’t written the logic for it. Instead of writing the code, you must simply add the header file, i.e., fname.h, using #include and double-quotes. Then, you must save it with the .cpp extension.
After saving the file, run the code, and below is the output of the code, i.e., the average of three numbers.
Learn right from the basics of JavaScript to advanced concepts of Angular, Spring Boot, Hibernate, JSPs, MVC, etc. Enroll in our PGP in Full Stack Web Development today!
Conclusion
After reading this tutorial on C++ Header files, you would have understood why you use Header files, what C++ Header files are, their syntax, and the types of Header files in C++. You also learned about the working of C++ Header files and how you can create your header file with the help of some examples.
Simplilearn’s Post Graduate Program in Full Stack Web Development will be ideal for you if you want a more comprehensive study that goes beyond Mobile and Software Development Delivered in collaborations with Caltech CTME, this online coding boot camp covers the most in-demand programming languages and skills needed for success in software development today. It’s time to get out there and explore.
Do you have any questions regarding this tutorial on C++ Header files? If you do, then please put them in the comments section. We’ll help you solve your queries. To learn more about C++ Header files, click on the following link: C++ Header files
Find our Full Stack Java Developer Online Bootcamp in top cities:
Name | Date | Place | |
---|---|---|---|
Full Stack Java Developer | Cohort starts on 4th Aug 2023, Weekend batch | Your City | View Details |
Full Stack Java Developer | Cohort starts on 25th Aug 2023, Weekend batch | Your City | View Details |
About the Author
Kartik Menon
Kartik is an experienced content strategist and an accomplished technology marketing specialist passionate about designing engaging user experiences with integrated marketing and communication solutions.