在程序设计过程中,经常需要设置预定义宏来返回程序的某些状态,以方便交叉编译和调试,比如用__func__打印该函数和__LINE__打印该行行数,以定位程序中打印该信息的函数和位置:
myPrintf(MY_PRINTF_DEBUG,"%s(%d):enFlag = %d\r\n",__func__,__LINE__,userGlobalParameter.encryptionFlag);
/*
__func__:C99 标准提供一个名为_ _func_ _的预定义标识符, 它展开为一个代表函数名的字符串(该函数包含该标识符) 。 那么, _ _func_ _必须具有函数作用域, 而从本质上看宏具有文件作用域。 因此, _ _func_ _是C语言的预定义标识符, 而不是预定义宏。
*/
那么,C中还有哪些预定义宏提供我们去更方便的进行程序设计呢?
例如:
#include <stdio.h>
int main()
{
printf("The file is %s.\r\n", __FILE__); //文件及路径
printf("The date is %s.\r\n", __DATE__); //日期
printf("The time is %s.\r\n", __TIME__); //时间
//printf("The version is %ld.\r\n", __STDC_VERSION__); //C版本
printf("This is line %d.\r\n", __LINE__); //line数
printf("This function is %s\r\n", __func__); // main标识符,函数自带
return 0;
}
运行结果如下:
另可以用#line重定义__LINE__的行数, 用#error 产生报错信息,例如:
#include <stdio.h>
int main()
{
printf("The date is %s.\r\n", __DATE__);
printf("The time is %s.\r\n", __TIME__);
//printf("The version is %ld.\r\n", __STDC_VERSION__);
#line 1000 "cool.c" //重定义行数和文件名
printf("This is line %d.\r\n", __LINE__);
printf("The file is %s.\r\n", __FILE__);
#if __LINE__==1000 //产生报错信息
#error Not 1000
#endif
printf("This function is %s\r\n", __func__);
return 0;
}
运行结果如下: