alan478
alan478

Reputation: 183

How to capture line number within existing code in C/C++?

I'm trying to perform some analysis of an existing program and need to log line numbers without modifying the program too much. I've been playing with __LINE__ and was hoping to do something like this:

file.h:

void Function( int iLine = __LINE___ );   // original function had no arguments, but now overloaded to default __LINE__

file.cpp:

void Function( int iLine ) {    // original function had no arguments, but now changed to int iLine
    // do something here
    // log iLine number to a file for analysis
}

main.cpp call:

Function();    // call existing function

However, I now know this is not going to work as iLine is always the file.h definition line number.

I've tried StackWalker, but also had difficulty and seemed a little overkill.

Any suggestions on how to approach this while keeping original file changes minimal?

Upvotes: 3

Views: 102

Answers (2)

Mike Nakis
Mike Nakis

Reputation: 62130

You can look at how the ASSERT() macro is defined.

If I remember well, it is something like this:

#define ASSERT(x) _assert( (x), __FILE__, __LINE__ );
void _assert( bool expression, const char* pfile, int line );

So, the ASSERT() macro is used as a wrapper for the _assert() function, so it is expanded at the call site, and it is irrelevant whether the target function gets inlined or not.

Upvotes: 1

eerorika
eerorika

Reputation: 238461

Option 1: Use a function like macro instead of a function. The macro will expand into the "call" site, thus giving the correct line. The macro itself may be as simple as passing the argument into a proper function.

Option 2: Use std::source_location instead, which will be introduced in the upcoming c++20.

Upvotes: 3

Related Questions