1. 原始代码
// demo2.h
#include <iostream>
void testFunc(int num)
{
std::cout << num << std::endl;
}
//main.cc
#include "demo2.h"
void func1()
{ }
void func2()
{
testFunc(24);
}
int main()
{
func1();
func2();
return 0;
}
- 我现在需要知道
testFunc
是在哪一行被调用了。
2. 使用 define
实现
#include <iostream>
#define testFunc(num) __testFunc(num, __FILE__, __FUNCTION__, __LINE__)
void __testFunc(int num, const char* fileName, const char* funcName, int line)
{
std::cout << fileName << std::endl;
std::cout << funcName << "()" << std::endl;
std::cout << "line: " << line << std::endl;
std::cout << num << std::endl;
}
- 主函数一样
#include "demo2.h"
void func1()
{ }
void func2()
{
testFunc(24);
}
int main()
{
func1();
func2();
return 0;
}
如此就实现了打印函数在娜个文件、哪个函数哪一行被调用的效果
作为 debug 的时候很有用,比如下面的代码:
#include <stdio.h>
/**
* @brief 支持预定义标识符
*
__FILE__ : 表示进行编译的源文件字符串
__FUNCTION__ : 表示所在函数
__LINE__ : 表示当前文件的行号
__DATE__: 表示文件日期
__TIME__ : 表示文件时间
*/
#define DEBUG_LOG(fmt, args...) \
do \
{ \
printf("[debug] %s:%d func: %s(): ", __FILE__, __LINE__, __FUNCTION__); \
printf(fmt, ##args); \
} while (0)
void print_str(const char* pStr)
{
if (NULL == pStr)
{
DEBUG_LOG("pStr is NULL\n");
return;
}
printf("%s\n", pStr);
}
int main()
{
// [debug] func: print_str() line25 pStr is NULL
print_str(NULL); // 在这里,它传进一个 NULL,非法,会在函数内部报错,但是我们又想知道是哪一行报的错,__LINE__ 和 __FUNCTION__ 就非常有用
// 小小滴熊
print_str("小小滴熊");
return 0;
}
输出:
[debug] func: print_str() line25 pStr is NULL
小小滴熊