A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
#ifdef checks whether a macro is defined. #ifndef checks whether it is not defined. The code between the directive and the matching #endif is included or excluded from compilation based on the result. This is how you write platform-specific code, enable debug features, and prevent header files from being included twice. The preprocessor runs before the compiler. Excluded code is not compiled, not syntax-checked, and does not exist in the binary.
#include <stdio.h>int main(void) {#ifdef _WIN32printf("Running on Windows\n");#elif defined(__linux__)printf("Running on Linux\n");#elif defined(__APPLE__)printf("Running on macOS\n");#elseprintf("Running on unknown platform\n");#endif#ifdef DEBUGprintf("Debug mode enabled\n");#endifreturn 0;}
The -DDEBUG flag defines the DEBUG macro on the command line. The #ifdef DEBUG block is included. Without the flag, the block is excluded. The compiler never sees the printf inside the excluded block. It does not check its syntax. It does not allocate space for its string literal. The code does not exist.
#ifndef CONFIG_H#define CONFIG_H#define MAX_CONNECTIONS 100#define TIMEOUT_MS 5000typedef struct {int port;int debug;} Config;#endif
The first time config.h is included, CONFIG_H is not defined. The #ifndef passes. The contents are processed. CONFIG_H is defined. The second time config.h is included (perhaps indirectly through another header), CONFIG_H is already defined. The #ifndef fails. Everything between it and #endif is skipped. The struct is not redefined. The constants are not redeclared. No duplicate symbol errors. This is the include guard pattern, and every header file you write must have one.
#ifdef and #ifndef are the gates of conditional compilation. They control what the compiler sees. Platform detection, feature flags, debug code, include guards: all built on these two directives. Next: #if, #elif, #else, which extend conditional compilation to arbitrary constant expressions.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.