C++ Preprocessor Directives: Conditional Compilation and Source Transformation
What is C++ Preprocessor Directives: Conditional Compilation and Source Transformation? Preprocessor directives are instructions preceded by # executed before compilation starts. They perform textual source code manipulation, file inclusion (#inclu...
What are preprocessor directives in C++ and how are #define, #ifdef, #ifndef, and #pragma used?
Explanation & In-Depth Details
```text
Source Code (.cpp/.hpp) ──► [ PREPROCESSOR ] ──► Expanded Source ──► [ COMPILER ]
│
• Replaces #include with file text
• Evaluates #ifdef / #if conditions
• Strips comments & expands macros
```
2. Modern C++ Recommendations:
- Replace macro constants (`#define PI 3.14`) with `constexpr double PI = 3.14;`.
- Replace function macros (`#define SQUARE(x) ((x)*(x))`) with `inline` or `constexpr` functions.
Code Example
#include <iostream>
#define ENVIRONMENT_PRODUCTION 1
// Macro with stringification and line logging
#define LOG_DEBUG(msg) std::cout << "[DEBUG] " << __FILE__ << ":" << __LINE__ << " - " << msg << "\n"
int main() {
#ifdef ENVIRONMENT_PRODUCTION
std::cout << "Running in PRODUCTION environment mode.\n";
#else
std::cout << "Running in DEVELOPMENT debug mode.\n";
#endif
LOG_DEBUG("System initialized successfully.");
std::cout << "C++ Standard Version: " << __cplusplus << "\n";
return 0;
}Interview Question & Tips
A: `constexpr` variables are strongly typed, obey standard scope and namespace rules, and generate readable compiler error messages, unlike untyped text-substituting macros.
Q: What is the purpose of conditional compilation (`#ifdef DEBUG`)?
A: It allows developers to include debug assertions, profiling hooks, or OS-specific code during development without including unnecessary binary overhead in release builds.
Best Practices
• Use conditional compilation sparingly for platform checks (`#ifdef _WIN32`) and debug builds (`#ifndef NDEBUG`).
• Always wrap macro arguments in parentheses if macros must be written.
This study reference for C++ Preprocessor Directives: Conditional Compilation and Source Transformation is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: