Basics
C++ Preprocessor
Using Preprocessor
C++ preprocessor uses #include and #define for macros.
Introduction to C++ Preprocessor
The C++ preprocessor is a powerful tool that processes your code before it is compiled. It performs textual substitutions, file inclusions, and conditional compilations. Using preprocessor directives, you can modify the code based on certain conditions or include external files. The most common preprocessor directives are #include
and #define
.
Using #include Directive
The #include
directive is used to include the contents of a file in the program. This is typically used to include header files which contain declarations for functions and macros. There are two forms of the #include
directive:
- Using angle brackets:
#include <filename>
- This searches for the file in standard system directories. - Using quotes:
#include "filename"
- This searches for the file in the current directory first, then in the standard system directories.
Defining Macros with #define
The #define
directive is used to define macros. Macros are essentially placeholders or constants that are replaced by their values during preprocessing. They can be defined for simple value substitutions or more complex functions.
For example, you can define a macro for a constant:
Macros can also be parameterized to act like functions:
Conditional Compilation
Conditional compilation is another powerful feature of the preprocessor. It allows you to compile code selectively based on certain conditions. This is done using directives like #ifdef
, #ifndef
, #endif
, #else
, and #elif
.
Here's an example that uses #ifdef
to include code only if a macro is defined:
In the above example, the LOG
macro will output to the console only if DEBUG
is defined. Otherwise, it does nothing.
Basics
- Previous
- Security Basics
- Next
- Namespaces