条件编译
条件编译根据宏定义选择性地编译代码,用于跨平台适配、调试代码控制、功能开关等。条件编译是 C 语言实现可移植性和模块化编译的核心机制。
基本形式
#define DEBUG 1
#ifdef DEBUG
printf("Debug mode\n");
#endif
#ifndef RELEASE
printf("Not release mode\n");
#endif
#if 表达式
#define VERSION 2
#if VERSION >= 2
/* 版本 2+ 的代码 */
void new_feature(void);
#elif VERSION == 1
/* 版本 1 的代码 */
void old_feature(void);
#else
#error "Unsupported version"
#endif
平台适配
#ifdef _WIN32
#include <windows.h>
#define PATH_SEP '\\'
#elif defined(__linux__)
#include <unistd.h>
#define PATH_SEP '/'
#elif defined(__APPLE__)
#include <unistd.h>
#define PATH_SEP '/'
#else
#error "Unsupported platform"
#endif
调试代码控制
#ifdef DEBUG
#define DEBUG_PRINT(fmt, ...) printf("[DEBUG] " fmt "\n", __VA_ARGS__)
#else
#define DEBUG_PRINT(fmt, ...) ((void)0)
#endif
DEBUG_PRINT("x = %d", x); /* 只在 DEBUG 定义时输出 */
头文件保护
#ifndef MYHEADER_H
#define MYHEADER_H
/* 头文件内容 */
#endif /* MYHEADER_H */
常见错误
嵌套错误:
#ifdef A
#ifdef B
/* ... */
#endif
/* 忘记 #endif for A */
表达式错误:
#if x > 0 /* 错误:x 不是预处理器常量 */
/* ... */
#endif
最佳实践
- 头文件始终加保护
- 平台相关代码集中管理
- 调试宏统一命名
#error检查配置一致性- 条件编译层次不宜过深