C语言杂谈01---如何理解条件编译

本文介绍了C语言的条件编译,包括#define、#ifdef、#ifndef等指令的使用,阐述了条件编译的作用,如避免重复编译、实现移植性和代码切割特性,并通过实例解释了条件编译在实际开发中的应用。
摘要由CSDN通过智能技术生成

架构图

前言

由于地区翻译关係,有些书籍将macro翻译成"巨集",有些翻译成"宏",为了避免混淆(我自己),所以文章内容会以英文名macro来代替中文译名

甚麽是条件编译

条件编译就是根据已经定义的macro进行选择性判断的语句,它会在compiler进行编译前完成,主要由预处理器负责

预处理器会将条件编译指令的结果告诉compiler,让他去编译指定区段的程式码。条件编译指令可能会出现在程式的任何一个位置,端看使用方法,例如下方这个简单的程式范例就含有条件编译:

#include <stdio.h>

/*若a没有被定义就定义它*/
#ifndef a
#define a 1
#endif

int main(){
   
	#if (a == 1)
		printf("a == 1\n");
	#else
		printf("a != 1\n");
	#endif
	
	return 0;
}

和一般的条件语句不同的是,条件编译在compile之前就已经决定,相反的,正常的条件语句(if, else if, else…)需要我们在执行时(run time)才能进行判断

也就是说条件编译语句可以让compiler知道那些程式码区段需要编译,那些可以直接捨去;而正常的条件语句因为需要在执行时依照变数值去判断执行区块,所以无论如何整个逻辑区块都会被全部编译

下图我们看到一个.c档被编译成可执行档的过程,绿色区块就是条件编译主要涉及部分。条件编译有点超前部署的味道,它会决定谁会被包含、编译、忽略,它不被编译器编译,想当然也不属于C/C++范畴

条件编译种类

#if, #elif, #defined

#if, #elif利用后方的常数表达式(constant-expression)来判断程式码区段是否需要被包含

例如下面简单的程式码片段,因为test被定义成1,这个条件恰好吻合第一个区段,所以会编译并执行#if#else之间区段

#include <stdio.h>

#define test 1

int main(){
   
   #if (test == 1)
       printf("Macro test exist...");
   #else
		printf("Macro test is not defined...");
   #endif
}

输出结果:

Macro test exist...

#if后的常数表达式可以使用一元运算子进行判断,也可以使用逻辑运算子结合多个判断式。当判断条件超过两组时可以使用#elif, #else,和一般的if-else if-else语句没什麽分别

#include <stdio.h>

#define test1 10
#define test2 1

int main(){
   
   #if (test1 > 8) && (test1 < 15) && (test2 > 0)
       printf("Macro test meet the requirement");
   #elif(test1 > 15)
	   printf("Macro test meet the requirement, but way too big");
   #else
	   printf("Macro test doesn't meet the requirement");
   #endif
}

输出结果:

Macro test meet the requirement

切记#if后方的判断式要加上小括号()

#if还可以加上条件编译语句defined(),它用来判断一个macro是否被定义。例如我们把上面的程式码稍微改写一下:

#include <stdio.h>

#define test1 10
// #define test2 1

int main(){
   
   #if (test1 > 8) && (test1 < 15) && defined(test2)
       printf("Macro test meet the requirement");
   #elif(test1 > 15)
	   printf("Macro test meet the requirement, but way too big");
   #else
	   printf("Macro test doesn't meet the requirement");
   #endif
}

输出结果:

Macro test doesn't meet the requirement

由于test2被我们註解掉,所以实际上它没有被定义,所以最后输出结果没能满足#if#elif条件

一些常见问题
使用#if#defined的时机其实有点不同,前者单独使用必须搭配表达式,对macro的进行判断;后者仅用来判断macro是否被定义

假设我们想用#if来代替#defined判断一个test2是否被定义:

#include <stdio.h>

#define test1 1
#define test2 2

int main(){
   
    #if defined(test1) && (test2)
        printf("success\n");
    #else
        printf(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值