C语言预处理 条件编译

条件编译用于在 编译阶段 控制代码的编译行为,可以根据不同的 平台、环境、宏定义 选择性地编译部分代码。

主要预处理指令

指令作用
#ifdef如果宏被定义,则编译
#ifndef如果宏未定义,则编译
#if进行条件判断
#elifelse if,如果前面条件不满足,则判断当前
#elseelse,前面所有条件不满足时执行
#endif结束条件编译

基本示例:

#include <stdio.h>

#define DEBUG  // 定义 DEBUG 宏

int main() {
#ifdef DEBUG
    printf("调试模式开启\n");
#endif

#ifndef RELEASE
    printf("非发布模式\n");
#endif

    return 0;
}

编译时使用 -D 定义宏

gcc main.c -o main -DDEBUG

-DDEBUG 相当于 #define DEBUG,启用 #ifdef DEBUG 部分代码

#if 进行数值判断

#include <stdio.h>

#define VERSION 2

int main() {
#if VERSION == 1
    printf("版本 1\n");
#elif VERSION == 2
    printf("版本 2\n");
#else
    printf("未知版本\n");
#endif
    return 0;
}

适配不同平台

#include <stdio.h>

int main() {
#ifdef _WIN32
    printf("Windows 平台\n");
#elif __linux__
    printf("Linux 平台\n");
#elif __APPLE__
    printf("Mac 平台\n");
#else
    printf("未知平台\n");
#endif
    return 0;
}

避免重复包含头文件(#ifndef 方式)

#ifndef MAIN_H
#define MAIN_H

// 头文件内容

#endif // MAIN_H

保证头文件只被包含一次,避免重复定义错误

总结

  • #ifdef / #ifndef 检测是否定义
  • #if / #elif 进行条件判断
  • 适用于 跨平台开发、调试模式、头文件保护
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容