cpp-directivas-precompilacion

Precompilation Directives in C++

  • 2 min

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 for them to be overused.

Tip: use as few as possible, and only when their use is indispensable.

Syntax of Preprocessor Directives

Preprocessor directives in C++ are commands that begin 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
Copied!
  • Standard Files: Files included with <> are searched for in the system’s standard directories.
  • Local Files: Files included with "" are searched for in the directory of the current source file.
#include <iostream>  // Inclusion of the standard input/output library

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
Copied!

In this example, #include <iostream> includes the standard input/output library which provides the functionality for printing 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;
}
Copied!

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 code snippets or constants that are substituted during the preprocessing stage.

#define MACRO_NAME value
Copied!

While the #undef directive is used to undefine a macro.

#undef MACRO_NAME
Copied!

If you want to know more, check out this entry.