小记C语言中的宏定义及条件编译
2019-11-02 16:48:43

普通宏定义

1
2
3
4
5
6
7
8
9
#define PI 3.14
#define a (1+2) //添加括号使语义表达更清楚

printf("%s:%d","PI",PI); //引号中的宏定义不会被替换,输出:PI:3.14
#undef PI //取消PI的宏定义

#define 1111 F //报错,宏定义起始位不能为数字
#define word "apple //宏定义中引号必须成对出现
#define char ‘a

带参数的宏定义

1
2
3
4
5
6
7
8
#define MAX(a,b)	(a>b ? a:b)

#define MIN(a,b) (a<b ? a:b)

int main(){
int sum = MAX(1,2) + MIN(2,3);
return 0;
}

当宏定义需要多行的代码时,可以用\来连接:

1
2
3
4
5
6
7
8
9
10
11
12
#define SWAP(a,b)   {\
int t = 0; \
t = a; \
a = b; \
b = t; \
}
int main(){
int x = 2,y = 3;
SWAP(x,y);
printf("%d,%d",x,y);
return 0;
}

宏定义中的特殊符号

1
2
3
4
5
6
#define TOSTRING(a)		#a
#define CONNECT(a,b) a##b
int main(){
char *str0 = TOSTRING(hello);
char *str1 = CONNECT("hello","world");
}

宏定义实现条件编译

基本用法

条件编译的控制与if-else语句相似,只不过控制的是是否将其后的代码段进行编译。

1
2
3
4
5
#if (判断条件)
{code}
#else
{code}
#endif
1
2
3
4
5
6
7
8

#if (判断条件1)
{code}
#elif (判断条件2)
{code}
#else
{code}
#endif

其他用法

if define等价于ifdefifndef等价于if !define()

1
2
3
4
5
6
7
#if defined(PI)  //  如果前面已经定义过PI这个宏,就将code编译进去。
{code}
#endif

#if defined(PI) // 如果前面没有定义过PI这个宏,就将code编译进去。
{code}
#endif

防止头文件重复引入的三种方法

1
2
3
4
#ifndef _HEADER		//_HEADER为自定义的名称
#define _HEADER
/*头文件其余内容*/
#endif
Prev
2019-11-02 16:48:43
Next