C++ Header Files
Header files in C++ contain declarations of functions, classes, constants, and macros. They allow code to be modular, reusable, and organized. You can include them in your source files using the #include directive.
1. Standard Header Files
C++ provides a rich set of standard header files in the standard library. These headers contain pre-defined classes, functions, and objects for common tasks.
| Header | Purpose | Example |
|---|---|---|
| Input/Output streams | cout, cin, cerr | |
| Mathematical functions | sqrt(), pow(), sin() | |
| String class and functions | std::string, getline() | |
| Dynamic array container | std::vector | |
| Common algorithms | sort(), find(), max_element() | |
| File handling | ifstream, ofstream, fstream | |
| Input/output formatting | setw(), setprecision() |
2. Custom Header Files
You can create your own header files to store declarations and reuse them across multiple source files. Typically, custom headers have the .h extension.
C++
Creating and including a custom header
// myfunctions.h
#ifndef MYFUNCTIONS_H
#define MYFUNCTIONS_H
void greet();
#endif
// main.cpp
#include <iostream>
#include "myfunctions.h"
using namespace std;
void greet() {
cout << "Hello from header file!" << endl;
}
int main() {
greet();
return 0;
}
3. Including Header Files
- Use angle brackets
< >for standard library headers:#include <iostream> - Use double quotes
" "for custom headers:#include "myheader.h" - Header guards prevent multiple inclusion of the same header in a project.
4. Complete Example Program
C++
Using standard and custom header files
// utils.h
#ifndef UTILS_H
#define UTILS_H
void printMessage();
#endif
// utils.cpp
#include <iostream>
#include "utils.h"
using namespace std;
void printMessage() { cout << "Hello from utils!" << endl; }
// main.cpp
#include <iostream>
#include "utils.h"
using namespace std;
int main() {
printMessage();
return 0;
}
Conclusion
C++ header files allow modular programming by separating declarations from implementation. Using standard and custom headers properly improves code organization, reusability, and readability.
Codecrown