C语言宏定义-跟踪调试宏
1. 简介
标准C语言预处理要求定义某些对象宏,每个预定义宏的名称一两个下划线字符开头和结尾,这些预定义宏不能被取消定义(#undef)或由编程人员重新定义。
__LINE__ | 当前代码行的行号,表示为十进制整型常量, 注:#line 可以重新设定__LINE__ 的值 |
---|---|
__FILE__ | 当前代码的文件名(全路径),表示字符串型常量 |
__func__ or __FUNCTION__ | 当前代码所在的函数名,表示字符串常量 |
__DATE__ | 转换的日历日期,表示为Mmm dd yyyy 形式的字符串常量,Mmm是由asctime产生的 |
__TIME__ | 转换的时间,表示"hh:mm:ss"形式的字符串型常量,是有asctime产生的 |
__cplusplus | 指示c++编译器 |
2. 相关宏
/**
* @def CMO_STRFILE
* @brief Provide a string identifying the current code filename.
*/
#define CMO_STRFILE ((const char *)(__FILE__))
/**
* @def CMO_STRFUNC
* @brief Provide a string identifying the current function.
*/
#define CMO_STRFUNC ((const char *)(__FUNCTION__))
/**
* @def CMO_INTLINE
* @brief Provide a int identifying the current code filename.
*/
#define CMO_INTLINE ((int)(__LINE__))
/**
* @def CMO_STRLINE
* @brief Provide a string identifying the current code line.
*/
#define CMO_STRLINE CMO_STRINGIFY(__LINE__)
/**
* @def CMO_STRLOC
* @brief Provide a string identifying the current code position.
*/
#define CMO_STRLOC __FILE__ ":" CMO_STRINGIFY(__LINE__)
/**
* @def CMO_STRDATETIME
* @brief Provide a string identifying the current build date time.
*/
#define CMO_STRDATETIME __DATE__ "T" __TIME__
3. 例子
#include <stdio.h>
/**
* @def CMO_STRINGIFY
* @brief converts a macro argument into a character constant.
*
* @param[in] x - A macro argument to stringify.
*/
#define CMO_STRINGIFY(x) CMO_STRINGIFY_(x)
/** Auxiliary macro used by @ref CMO_STRINGIFY */
#define CMO_STRINGIFY_(x) #x
/**
* @def CMO_STRFILE
* @brief Provide a string identifying the current code filename.
*/
#define CMO_STRFILE ((const char *)(__FILE__))
/**
* @def CMO_STRFUNC
* @brief Provide a string identifying the current function.
*/
#define CMO_STRFUNC ((const char *)(__FUNCTION__))
/**
* @def CMO_INTLINE
* @brief Provide a int identifying the current code filename.
*/
#define CMO_INTLINE ((int)(__LINE__))
/**
* @def CMO_STRLINE
* @brief Provide a string identifying the current code line.
*/
#define CMO_STRLINE CMO_STRINGIFY(__LINE__)
/**
* @def CMO_STRLOC
* @brief Provide a string identifying the current code position.
*/
#define CMO_STRLOC __FILE__ ":" CMO_STRINGIFY(__LINE__)
/**
* @def CMO_STRDATETIME
* @brief Provide a string identifying the current build date time.
*/
#define CMO_STRDATETIME __DATE__ "T" __TIME__
int main (void)
{
printf("%-16.16s: %s\n", "CMO_STRFILE", CMO_STRFILE);
printf("%-16.16s: %s\n", "CMO_STRFUNC", CMO_STRFUNC);
printf("%-16.16s: %d\n", "CMO_INTLINE", CMO_INTLINE);
printf("%-16.16s: %s\n", "CMO_STRLINE", CMO_STRLINE);
printf("%-16.16s: %s\n", "CMO_STRLOC", CMO_STRLOC);
printf("%-16.16s: %s\n", "CMO_STRDATETIME", CMO_STRDATETIME);
return (0);
}
// gcc -o test test.c && ./test
运行结果: