Create Header Files
Posted on December 3, 2022 • 2 minutes • 348 words
A header file contains the declarations and definitions of functions and macros.
Types:
- System header files.
Example : iostream
, vector
, string
..etc.
- User defined header files.
How to use header files
We use a special pre-processor directive called #include to use/include header files.
Syntax for System header files:
#include <header_file_name>
Example:
#include <iostream>
#include <vector>
Syntax for User defined header files:
#include "path/to/header_file_name.h"
Example:
#include "anooptube.h"
#include "my_header_file.h
Make your own header file and use it.
Example arithmetic.h
Step-1:
Create a file arithmetic.h
Step-2:
Define the functions
// arithmetic.h
int getSum(int x,int y)
{
return x + y;
}
Step-3:
- Create main file main.cpp
- include your header file arithmetic.h
- use the function you have defined getSum()
// main.cpp
#include <iostream>
#include "arithmetic.h"
int main()
{
std::cout << "Hello #anooptube!\n";
std::cout << "Sum: " << getSum(100, 150) << "\n";
return 0;
}
Issue of multiple definition error
- If you make a second header file sum.h and include
arithmetic.h
file
// sum.h
#include <iostream>
#include "arithmetic.h"
void getMySum(int x,int y)
{
// function in arithmetic.h
std::cout << "Sum : " << getSum(x,y);
}
- and include
sum.h
inmain.cpp
, to usegetMySum()
, we get a multiple-definition error
#include <iostream>
#include "arithmetic.h"
#include "sum.h"
int main() {
std::cout << "Hello World!\n";
// function in arithmetic.h
std::cout << getSum(100, 150) << "\n";
// function in sum.h
getMySum(100, 150);
}
This error is due to including arithmetic.h
two times in the mai.cpp file by
- including of
arithmetic.h
- including of
sum.h
(sum.h
already includedarithmetic.h
).
To avoid this error we have to use header guards
Header Gurads
Syntax:
#ifndef UNIQUE_NAME
#define UNIQUE_NAME
// body of header file goes here
#endif
Example
arithmetic.h
#ifndef ANOOP_TUBE_ARITHMETIC_H
#define ANOOP_TUBE_ARITHMETIC_H
int getSum(int x,int y)
{
return x + y;
}
#endif
sum.h
// sum.h
#ifndef ANOOP_TUBE_SUM_H
#define ANOOP_TUBE_SUM_H
#include <iostream>
#include "arithmetic.h"
void getMySum(int x,int y)
{
// function in arithmetic.h
std::cout << "Sum : " << getSum(x,y);
}
#endif
These changes solve the issue of multiple-definition error.
Well done! You’ve mastered the header files.