#ifdef vs #if defined()
What is the difference between #ifdef and #if defined() in C++?
Both #ifdef and #if defined() are used for conditional compilation in C++, but they have a slight difference in syntax.
The #ifdef MACRO checks if MACRO is defined. If it is, the code block following the directive is included in the compilation.
#include <iostream>
#define DEBUG
int main() {
#ifdef DEBUG
std::cout << "Debug mode is on\n";
#endif
}Debug mode is on#if defined(MACRO) also checks if MACRO is defined, but it allows for more complex expressions.
#include <iostream>
#define DEBUG
int main() {
#if defined(DEBUG) && !defined(RELEASE)
std::cout << "Debug mode is on,"
" Release mode is off\n";
#endif
}Debug mode is on, Release mode is offIn most cases, #ifdef and #if defined() can be used interchangeably. However, #if defined() provides more flexibility when combining multiple conditions using logical operators like && and ||.
Preprocessor Directives and the Build Process
Learn the fundamentals of the C++ build process, including the roles of the preprocessor, compiler, and linker.