#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 语句可以用它区隔一些与特定头文件、程序库和其他文件版本有关的代码