December 3, 2022

Create Header Files

Posted on December 3, 2022  •  2 minutes  • 329 words

A header file contains the declarations and definitions of functions and macros.

Types:

  1. System header files.

Example : iostream , vector, string ..etc.

  1. 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:

  1. Create main file main.cpp
  2. include your header file arithmetic.h
  3. 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

  1. 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);
}
  1. and include sum.h in main.cpp, to use getMySum(), 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

  1. including of arithmetic.h
  2. including of sum.h ( sum.h already included arithmetic.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

  1. arithmetic.h
#ifndef ANOOP_TUBE_ARITHMETIC_H
#define ANOOP_TUBE_ARITHMETIC_H

int getSum(int x,int y)
{
  return x + y;
}

#endif
  1. 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.

Follow me

I work on everything coding and share developer memes