6

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?

Qualphey
  • 1,244
  • 1
  • 19
  • 44
  • 3
    `__FILE__` and `__LINE__` respectively. – David G Jan 09 '14 at 14:10
  • For C++20: https://stackoverflow.com/a/58556021/5267751 – user202729 Dec 30 '19 at 03:52
  • This should not be a duplicate because it's not sufficient to just use those macros, it's also necessary to "hide the function behind a macro" (see the accepted answer) And that's not the only possible answer, there's another answer in C++20 which would not be appropriate for the other question (see the comment above) – user202729 Dec 30 '19 at 03:55

2 Answers2

15

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__)
Community
  • 1
  • 1
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

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

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

Jay
  • 601
  • 6
  • 17