Assume I have a class definition like this:
class A {
void method();
}
Assume I need to find where this method is called directly from C++ (i.e gdb and company are rulled out, so is throwing an exception)
One could naively define the following:
class A {
//void method();
void method() { print(__FILE__ + ": " + __LINE__) };
}
This will however print the file and line of the current method, not the file and line of where the method is called.
If instead of OOP our code was procedural once could convert:
void method();
To:
#define method() { print(__FILE__ + ": " + __LINE__) };
The above works because method takes in no parameters, so it;s easy for the peprocessor to change all instances of the method to our new debugging code.
However this is not very general. With OOP we can have classes A, B, C and D all overwriting the method, thus overprinting information for unrelated classes.
Even if only class A implements method()
if the function takes any parameters, now we get a new issue: method(int i)
would require a regular expression to be replaced since we have no prior knowledge of the variable names bassed into the method. i.e the pattern a.method(variable);
cannot be statically matched by a constant define, we would need to match regular expressions.
Does anyone know if it is possible to trick the compiler into resolving the __FILE__
and __LINE__
macros at the call rather than the definition?
EDIT:
The question marked as duplicate is from 2010, I think it's worth keeping this one open, 9 years seems more than enough time for new potential answers to be given to this question.
for example std::experimental::source_location
doesn't appear in the question.
I would like this question to be reopened