In C++, preprocessor directives are special instructions that the preprocessor, a stage prior to compilation, uses to modify the source code before the compiler processes it.
- File inclusion: Allows including header files and other necessary files.
- Compilation conditions: Allows compiling different parts of the code depending on certain conditions.
- Macro definition: Allows defining constants and macros to simplify the code.
Preprocessor directives are very powerful tools for managing code configuration. However, it is also very common to abuse them.
Tip, use as few as possible, and only when their use is essential
Syntax of Preprocessor Directives
Preprocessor directives in C++ are commands that start with the #
symbol and are interpreted by the preprocessor before the code is compiled.
Inclusion Directives
The #include
directive is used to include header files or other source files in the current file.
#include <file.h> // Includes standard header files
#include "file.h" // Includes local files
- Standard Files: Files included with
<>
are searched in the system’s standard directories. - Local Files: Files included with
""
are searched in the current source file’s directory.
#include <iostream> // Inclusion of the standard input/output library
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
In this example, #include <iostream>
includes the standard input/output library that provides functionality to print to the console.
Compilation Conditions
These directives #ifdef
, #ifndef
, #if
, #else
, #elif
, #endif
are used to include or exclude parts of the code depending on certain conditions.
#define DEBUG
int main() {
#ifdef DEBUG
std::cout << "Debug mode activated" << std::endl;
#endif
return 0;
}
In this example, the message “Debug mode activated” will only be printed if DEBUG
has been defined.
Macro Definition
The #define
directive is used to define macros, which are snippets of code or constants that are replaced during the preprocessing stage.
#define MACRO_NAME value
While the #undef
directive is used to undo the definition of a macro.
#undef MACRO_NAME
We will see macros in their own article read more ⯈