How to Use #include in C++: Syntax and Examples
In C++, use the
#include directive to insert the contents of a header file or library into your program before compilation. Use angle brackets <> for standard libraries and double quotes "" for your own files.Syntax
The #include directive tells the compiler to include the contents of another file. It has two main forms:
#include <filename>: Includes standard library headers or system files.#include "filename": Includes user-defined or local files.
The included file's code is copied into your source file before compilation.
cpp
#include <iostream>
#include "myheader.h"Example
This example shows how to include the standard iostream header to use std::cout for printing text.
cpp
#include <iostream> int main() { std::cout << "Hello, world!" << std::endl; return 0; }
Output
Hello, world!
Common Pitfalls
Common mistakes when using #include include:
- Using double quotes for standard libraries or angle brackets for local files, which can cause the compiler to not find the file.
- Including the same header multiple times without include guards, leading to redefinition errors.
- Forgetting to provide the correct path or filename.
cpp
#include "iostream" // Wrong for standard library #include <myheader.h> // Wrong for local file // Correct usage: #include <iostream> #include "myheader.h"
Quick Reference
| Usage | Description |
|---|---|
| #include | Includes standard or system header files |
| #include "filename" | Includes user-defined or local header files |
| Use include guards | Prevent multiple inclusions of the same header |
| Place #include at the top | Ensure dependencies are loaded before use |
Key Takeaways
Use #include to insert header files before compilation.
Use angle brackets for standard libraries and quotes for your own files.
Always use include guards to avoid multiple inclusion errors.
Place #include directives at the top of your source files.
Check file paths and names carefully to avoid compiler errors.