c语言的宏

C语言的宏

宏是一个字符串替换的工具,再编译之前,预处理阶段完成。
以#define起始的行为宏的定义。
宏中出现的几个特殊符号

  • ## 字符串拼接
  • # 符号转换为双引号包含的字符串
  • ... 变参展开

预处理前

#define MAX 1024
#define max(x, y) {(x) > (y) ? (x) : (y); MAX; MIN}
#define MIN 0

#define kh_destroy(name, h) kh_destroy_##name(h)
#define DEBUG_VALUE(v) printf(#v"is equal to %d.\n",v)
#define myprintf(templt,...) fprintf(stderr,templt,__VA_ARGS__)

#define myprintf2(templt,args...) fprintf(stderr,templt,args)


int x = MAX;
int y = max(3, 8);
kh_destroy(int,  h);
DEBUG_VALUE(y);
myprintf("%d%s", x, "h");
myprintf2("%d%s!", x, "h");

预处理命令

gcc -E macro.c -o macro.i

预处理后

# 1 "macro.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "macro.c"
# 12 "macro.c"
int x = 1024;
int y = {(3) > (8) ? (3) : (8); 1024; 0};
kh_destroy_int(h);
printf("y""is equal to %d.\n",y);
fprintf(stderr,"%d%s",x, "h");
fprintf(stderr,"%d%s!",x, "h");
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容