C Language | Preprocessing | Conditional Compilation - defined

Conditional compilation selects which source code is compiled. It is useful for debug builds, release builds, and platform-specific code.

Controlling Compilation

Use #if and #endif with a constant expression.

#if constant-expression
 code
#endif

Code 1

#include <stdio.h>
#define DEBUG_MODE 1

int main() {
#if DEBUG_MODE
 printf("Debug mode\n");
#endif
 return 0;
}

Use #else for an alternative and #elif for additional conditions.

#if LANG == EN
 printf("Kitty on your lap\n");
#elif LANG == KO
 printf("당신의 무릎 위에 고양이\n");
#else
 printf("Unsupported language\n");
#endif

Checking Definitions

A macro can be defined without replacement text.

#define DEBUG

Use defined inside #if, or use the shorter #ifdef and #ifndef directives.

#if defined(DEBUG)
 printf("Debug mode\n");
#endif

#ifdef DEBUG
 printf("Debug mode\n");
#endif

#ifndef compiles code when a name is not defined. This is commonly used for header guards.

Reporting Configuration Errors

Use #error when compilation must stop because a required setting is missing.

#ifndef BUFFER_SIZE
#error BUFFER_SIZE must be defined.
#endif