What is #include in C++?
In C++, #include
is a preprocessor directive used to include the contents of a file (usually a header file) in the program before compilation. This allows you to access functions, classes, and other definitions from libraries and modules without having to redefine them.
Key Points about #include
:
-
Header Files: The most common use of
#include
is to include standard library header files (e.g.,<iostream>
,<vector>
,<string>
) or user-defined header files. For example:#include <iostream> // Standard library for input-output operations #include "myHeader.h" // User-defined header file
-
Angle Brackets vs. Quotes:
- Angle Brackets (
<>
): Used for including standard library headers or system files. The compiler searches for these files in standard library directories. - Quotes (
""
): Used for including user-defined header files. The compiler first searches in the current directory and then in standard directories.
- Angle Brackets (
-
Compile-Time Inclusion: The contents of the included file are copied into the source file at the point where
#include
is used, allowing the program to utilize the definitions from the included file. -
Avoiding Multiple Inclusions: To prevent multiple inclusions of the same header file, which can lead to errors, it's common to use include guards or
#pragma once
:// Using include guards #ifndef MYHEADER_H #define MYHEADER_H // Declarations #endif
-
Library Functions: Including libraries using
#include
gives you access to pre-written functions and classes, facilitating code reuse and improving development efficiency.
Example Usage:
Here’s a simple example that demonstrates the use of #include
:
#include <iostream> // Include the iostream library using namespace std; int main() { cout << "Hello, World!" << endl; // Outputs: Hello, World! return 0; }
Conclusion:
The #include
directive is fundamental in C++ programming, allowing developers to include and utilize code from external libraries and their own header files, thus promoting modular programming and code reuse.
Sources:
GET YOUR FREE
Coding Questions Catalog