#ifdef 语句使用方法

本文详细介绍了C语言预处理指令中的#ifdef语句,包括其格式、作用和用法。通过实例展示了如何使用#ifdef来控制代码块的编译,特别是在处理头文件包含和跨平台编程时的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#ifdef 语句

资料链接:https://baike.baidu.com/item/%23ifdef
https://bbs.csdn.net/topics/210046082
https://blog.csdn.net/qq_40584593/article/details/85217303
http://c.biancheng.net/view/1986.html

#ifdef 语句格式:

#ifdef expression //<标识>

execution1 //待执行语句1

#elif //else 语句可以省略

execution2 //待执行语句2

#else

execution3 //待执行语句3
 
#endif
#ifndef expression //<标识>
expression4
#endif

解释:

  • <标识>在理论上来说可以是自由命名的,但每个头文件的这个“标识”都应该是唯一的。标识的命名规则一般是头文件名全大写,前后加下划线,并把文件名中的“.”也变成下划线,如:stdio.h 应该改为 STDIO_H
  • 如果expression已经被宏定义,则执行 execution1 语句,反之则执行 execution2 语句。
  • #ifndef 就是 if not define, 和#ifdef用法相反,即:#ifndef 后面的语句为真,则不执行 expression4。

下面举几个例子

例:

#include<stdio.h>
int main(int argc,char *argv[]){
#ifdef FLAG
printf("hello world");
#endif
}

运行结果为:

Press any key to continue

因为FLAG未宏定义,“hello world"不会被打印出来,若加上宏定义,如:

#include<stdio.h>
#define FLAG 1
int main(int argc,char *argv[]){
#ifdef FLAG
printf("hello world");
#endif
}

此时,运行结果为:

hello world
Press any key to continue

#ifdef 语句的作用(用法)

  • 跨平台使用时,可以用#ifdef 语句判断当前使用环境,再执行对应语句,如:
#include <stdio.h>
int main(){
    #if _WIN32
        system("color 0c");
        printf("hello world");
    #elif __linux__
        printf("\033[22;31m hello world \033[22;30m");
    #else
        printf("hello world");
    #endif
    return 0;
}
  • 利用#ifdef /#endif将某程序功能模块(如<stdio.h>)包括进去,以向某用户提供该功能
    如:
#ifndef DEBUG
#include "program.c"
#include <stdio.h>
#endif
  • 使用#ifdef 语句可以用它区隔一些与特定头文件、程序库和其他文件版本有关的代码
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值