如何获取函数调用的文件名和行号

How to get the file name and a line number of a function call?

本文关键字:文件名 函数调用 何获取 获取      更新时间:2023-10-16

我在不同的源文件中有两个函数:

答.cpp

void A()
{
    B();
}

乙.cpp

void B()
{
    std::cout << "B() called from file: " << ??? << " line: " << ??? << std::endl;
}

如何获取呼叫的文件名和线路号?

通常,

您可以通过将函数隐藏在宏调用后面来自动执行此操作,该宏调用传递__FILE____LINE__

void _B(const char* file, int line) { ... } 
#define B() _B(__FILE__, __LINE__)

不过,这绝不是一个万无一失的解决方案。 开发人员可以直接调用_B,也可以从生成的代码、程序集等调用_B......可能没有有意义的文件/行号

OP 要求提供带参数的示例

void _C(int p1, char p2, const char* file, int line) { ... } 
#define C(p1, p2) _C(p1, p2, __FILE__, __LINE__)

代码: printf("%s(%d)--:",__FILE__,__LINE__);

参考:http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html