Concept Flow - Conditional compilation
Start
Check #ifdef or #ifndef
Compile block
Continue compilation
End
The compiler checks if a condition is true (#ifdef/#ifndef). If yes, it compiles the code block; if no, it skips it and continues.
#define DEBUG #ifdef DEBUG printf("Debug mode on\n"); #endif printf("Program running\n");
| Step | Directive | Condition | Result | Action | Output |
|---|---|---|---|---|---|
| 1 | #define DEBUG | N/A | DEBUG defined | Define DEBUG macro | |
| 2 | #ifdef DEBUG | Is DEBUG defined? | Yes | Compile next block | |
| 3 | printf("Debug mode on\n"); | N/A | N/A | Execute print | Debug mode on |
| 4 | #endif | N/A | End if | End conditional block | |
| 5 | printf("Program running\n"); | N/A | N/A | Execute print | Program running |
| 6 | End | N/A | N/A | Program ends |
| Macro | Start | After Step 1 | Final |
|---|---|---|---|
| DEBUG | undefined | defined | defined |
#ifdef MACRO // code compiles only if MACRO is defined #endif #ifndef MACRO // code compiles only if MACRO is NOT defined #endif Use #define MACRO to define macros. Conditional compilation controls which code is included before compiling.
#ifdef directive do in C conditional compilation?#ifdef usage#ifdef directive checks if a macro is defined.#ifdef block is included during compilation.#ifdef means "if defined" [OK]#ifdef means "if defined" [OK]#ifdef with #ifndefDEBUG is NOT defined?#ifndef means "if not defined".DEBUG#ifndef DEBUG checks if DEBUG is not defined.#ifndef means "if not defined" [OK]#ifndef to check if macro is NOT defined [OK]#ifdef instead of #ifndef#if !DEBUG which is invalid for macro existence#if with #ifndefFEATURE is defined?
#include <stdio.h>
#define FEATURE
int main() {
#ifdef FEATURE
printf("Feature is enabled\n");
#else
printf("Feature is disabled\n");
#endif
return 0;
}FEATURE is defined#define FEATURE, so FEATURE is defined.#ifdef FEATURE blockFEATURE is defined, the code inside #ifdef FEATURE runs, printing "Feature is enabled".#ifdef block [OK]#ifdef block runs [OK]#else block runs#include <stdio.h>
int main() {
#ifdef DEBUG
printf("Debug mode\n");
#else
printf("Release mode\n");
#endif
return 0;
}int main() { but does not have a closing } brace.#ifdef and #else directives are correctly used; missing #define DEBUG is not an error, just changes output.DEBUG is defined, otherwise it prints "Normal mode". Which code snippet correctly achieves this using conditional compilation?DEBUG is defined, else print "Normal mode".#ifdef DEBUG checks if DEBUG is defined and includes the first print statement; #else handles the other case.#ifdef for defined macro check [OK]#ifdef for defined, #else for else [OK]#ifndef which reverses logic#if DEBUG without macro value#if !DEBUG which is invalidPass the test and this pattern moves unknown