C
Beginner
1 min read
Conditional Compilation: #ifdef, #if, and #pragma
Example
#include <stdio.h>
/* Platform detection */
#if defined(_WIN32) || defined(_WIN64)
#define PLATFORM "Windows"
#define PATH_SEP '\\'
#elif defined(__APPLE__)
#define PLATFORM "macOS"
#define PATH_SEP '/'
#elif defined(__linux__)
#define PLATFORM "Linux"
#define PATH_SEP '/'
#else
#define PLATFORM "Unknown"
#define PATH_SEP '/'
#endif
/* Build configuration */
#ifdef DEBUG
#define LOG(fmt, ...) \
fprintf(stderr, "[DEBUG %s:%d] " fmt "\n", \
__FILE__, __LINE__, ##__VA_ARGS__)
#else
#define LOG(fmt, ...) /* no-op in release builds */
#endif
/* Version guard */
#define MY_VERSION 3
#if MY_VERSION < 2
#error "Version 2 or higher is required"
#endif
/* C/C++ compatible header */
#ifdef __cplusplus
extern "C" {
#endif
void library_function(void);
#ifdef __cplusplus
}
#endif
void library_function(void)
{
printf("library_function called on %s\n", PLATFORM);
}
int main(void)
{
printf("Platform: %s\n", PLATFORM);
printf("Path sep: '%c'\n", PATH_SEP);
printf("Version: %d\n", MY_VERSION);
LOG("main started, version=%d", MY_VERSION);
library_function();
/* Compile with -DDEBUG to see LOG output */
printf("Compile with -DDEBUG to enable debug logging.\n");
return 0;
}
Related Resources
This is the last lesson in this section.
Create a free account to earn a certificate