Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I have two functions in different source files:

a.cpp

void A()
{
    B();
}

b.cpp

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

How can I get the file name and line number of the call?

like image 200
Qualphey Avatar asked Jan 09 '14 14:01

Qualphey


1 Answers

In general you can do this automatically by hiding your function behind a macro call which passes allong the __FILE__ and __LINE__ values

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

This is by no means a foolproof solution though. It's possible for developers to call _B directly or for _B to be called from generated code, assembly, etc .... where there may be no meaningful file / line number

OP asked for an example with arguments

void _C(int p1, char p2, const char* file, int line) { ... } 
#define C(p1, p2) _C(p1, p2, __FILE__, __LINE__)
like image 197
JaredPar Avatar answered Nov 10 '22 06:11

JaredPar