1、宏定义中使用#符号,宏定义中使用#代表把参数变成一个字符串,宏定义中使用##代表把两个宏参数连接在一起。
具体用法:
#include<stdio.h>
#defineSTR(s) #s
#defineCONS(a, b) a##e##b
voidmain()
{
printf(STR(Hello)); => printf(“Hello”);
printf(“%d”,CONS(2,3)); => printf(“%d”, 2e3);
}
2、当宏参数是另一个宏的时候,需要注意,凡是宏定义里面用到#或者##的地方,宏参数不会再展开。
#include<stdio.h>
#defineINT_MAX 100
#defineSTR(s) #s
#defineA (2)
#defineCONS(a, b) a##e##b
voidmain()
{
printf(“%d”,STR(INT_MAX)); => printf(“%d”, “INT_MAX”);
printf(“%d”,CONS(A, A)); => printf(“%d”, AeA);
}
解决这个问题的方法很简单,中间加上一层转换即可。
#define_STR(s) STR(s)
printf(“%d”,_STR(INT_MAX)); => printf(“%d”, STR(100));
#define_CONS(a, b) CONS(a, b)
printf(“%d”,_CONS(A, A)); => printf(“%d”, CONS((2), (2)));
3、#和##的特殊应用
#define_A1(type, var, line) type var##line
#define_A0(type, line) _A1(type, _anonymous,line)
#defineA(type) _A0(type, __LINE__)
A(staticint) => _A0(static int, _anonymous, __LINE__) => _A1(staticint, _anonymous,70) => static int _anonymous70
C语言中的__LINE__用以指示本行语句在源文件中的位置信息,举例如下:
-
#include<stdio.h>
-
main()
-
{
-
printf("%d\n",__LINE__);
-
printf("%d\n",__LINE__);
-
printf("%d\n",__LINE__);
-
};
该程序在linux用gcc编译,在windows的vc6.0下编译都可以通过,执行结果都为:
7
8
9
还可以通过语句#line来重新设定__LINE__的值,举例如下:
-
#include<stdio.h>
-
#line200
-
main()
-
{
-
printf("%d\n",__LINE__);
-
printf("%d\n",__LINE__);
-
printf("%d\n",__LINE__);
-
};
编译执行后输出结果为:
202
203
204
C语言中的__FILE__用以指示本行语句所在源文件的文件名,举例如下(test.c):
-
#include<stdio.h>
-
intmain()
-
{
-
printf("%s\n",__FILE__);
-
}
在gcc编译生成a.out,执行后输出结果为:
test.c
在windows的vc6.0下编译执行结果为:
c:\documentsand settings\administrator\桌面\test.c
另外gcc还支持__func__,它指示所在的函数,但是这个关键字不被windows下的vc6.0支持.
-
#include<stdio.h>
-
voidmain()
-
{
-
printf("thisis print by function %s\n",__func__);
-
}
其编译后输出结果为
thisis print by function main
#defineFILL(a) {a, #a}
enumIDD{OPEN, CLOSE};
typedefstruct MSG
{
IDDid;
constchar *msg;
}MSG;
MSG_msg[] = {FILL(OPEN), FILL(CLOSE)};