Header Files

Header Files

In C++, header files are used to declare functions, classes, variables, and other entities that are defined in other source files. Header files are typically used to share declarations between files and to provide a modular structure for C++ programs.

A header file typically has a .h or .hpp file extension and contains declarations of functions, classes, and other entities that are defined in one or more source files. Here's an example of a simple header file:

#ifndef MY_HEADER_H
#define MY_HEADER_H

int add(int x, int y);

#endif

In this example, MY_HEADER_H is a preprocessor macro that is used to prevent the header file from being included multiple times in the same source file. The add() function is declared in the header file, but its implementation is defined in a separate source file.

To use a header file in a source file, you typically include the header file using the #include directive. For example:

#include "my_header.h"

int main() {
  int result = add(5, 10);
  return 0;
}

In this example, the my_header.h header file is included in the main.cpp source file. This allows the add() function to be called in the main() function.

Header files can also include other header files, which allows for a modular structure in C++ programs. For example: