宏定义的形式如下:
#define 名字 替换文本
这是一种最简单的宏替换 —— 后续所有出现名字记号的地方都将被替换为 替换文本 。 #define 指令中的名字与变量名的命名方式相同,替换文本可以是任意字符串。通常情况下, #define 指令占一行,替换文本是 #define 指令行尾部的所有剩余部分内容,但也可以把一个较长的宏定义分成若干行,这时需要在待续的行末尾加上一个反斜杠符 \ 。 #define 指令定义的名字的作用域从其定义点开始,到被编译的源文件的末尾处结束。宏定义中也可以使用前面出现的宏定义。替换只对记号进行,对括在引号中的字符串不起作用。例如,如果 YES 是一个通过 #define 指令定义过的名字,则在 printf("YES") 或 YESMAN 中将不执行替换。 替换文本可以是任意的,例如:
#define forever for (;;) /* infinite loop */
该语句为无限循环定义了一个新名字 forever 。
宏定义也可以带参数,这样可以对不同的宏调用使用不同的替换文本。例如,下列宏定义定义了一个宏 max :
#define max(A, B) ((A) > (B) ? (A) : (B))
root@ubuntu:~/arm# vim test.c #include<stdio.h> void test2() { printf("hello world \n "); } void show() { printf("hello world show \n "); } //#define show test2 #define test2 show int main() { test2(); show(); return 0; }
root@ubuntu:~/arm# gcc test.c -o test root@ubuntu:~/arm# ./test hello world show hello world show root@ubuntu:~/arm# ./test hello world show hello world show root@ubuntu:~/arm#
demo2
root@ubuntu:~/arm# cat test.c #include<stdio.h> void test2() { printf("hello world \n "); } void show() { printf("hello world show \n "); } #define show test2 //#define test2 show int main() { test2(); show(); return 0; }
root@ubuntu:~/arm# gcc test.c -o test root@ubuntu:~/arm# ./test hello world hello world root@ubuntu:~/arm#