宏定义与预处理命令
- 预处理阶段:处理宏定义与预处理命令;
- 编译期:检查代码,分析语法、语义等,最后生成.o或.obj文件;
- 链接期:链接所有的.o或.obj文件,生成可执行文件。
预处理命令 – 宏定义
定义符号常量
#define pi 3.1415926 #define max_n 10000
定义傻瓜表达式
#define max(a, b) (a) > (b) ? (a) : (b) #define s(a, b) a * b
定义代码段
为连接符
#define p(a) { printf("%dn", a); }
预定义的宏
常见的预定义的宏
示例:
#include<stdio.h> int main(){ //首次编译的时间 //[jun 10 2022 09:46:48] printf("[%s %s]n", __date__, __time__); //代码行号:文件名:函数名 //[6 : e:2023考研专业课c语言define.cpp : main] printf("[%d : %s : %s]n", __line__, __file__, __func__); return 0; }
函数 vs 宏定义
作用时期:函数作用在编译期,宏定义作用在预编译期;
使用:函数需要利用额外的栈,因此需要额外的时间开销,相比宏定义更加节约时间但会浪费更多空间;
预处理命令 – 条件式编译
示例:
#include<stdio.h> //定义debug宏 #define debug //判断是否定义了debug宏 #ifdef debug #define max_n 1000 #else #define max_n 100 #endif int main(){ int arr[max_n + 5] = {0}; //如果没定义了debug宏 则结果为 420 个字节 //如果定义了debug宏,则结果为 4020 个字节 printf("sizeof(arr) = %lu n", sizeof(arr)); return 0; }
示例
没有bug的max宏
#define max(a, b)({ __typeof(a) _a = a; __typeof(b) _b = b; _a > _b ? _a:_b; })
打印log的函数,输出所在函数及行号等信息
#include<stdio.h> //打开log宏 #define debug //条件式编译 //变参宏 //args加##后表连接 此时args可为空 #ifdef debug #define log(format, args...){ printf("[%s : %s : %d] ", __file__, __func__, __line__); printf(format, ##args); printf("n"); } #else #define log(format, args...) #endif int main(){ int a = 123, b = 13; //[e:2023考研专业课c语言log.cpp : main : 12] a = 123, b = 13 log("a = %d, b = %d", a, b); //[e:2023考研专业课c语言log.cpp : main : 13] hello log("hello"); return 0; }
到此这篇关于c语言详细分析宏定义与预处理命令的应用的文章就介绍到这了,更多相关c语言宏定义内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!
需要了解更多c/c++开发分享C语言详细分析宏定义与预处理命令的应用,都可以关注C/C++技术分享栏目—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/1237347.html