C++ and the callstack - can it be used to get line numbers?

610 Views Asked by At

I can't quite recall what library GCC works with to implement stack unwinding, which is used for c++ exceptions and call traces, and I know there's no means defined in the C++ specification, so any answers to this are platform specific. I am using GCC 4.9.0.

Knowing where something went wrong is very useful, especially during debugging. So quite often I'll have macros that expand and pass something __LINE__ and __FILE__ in the expansion.

I don't really like doing this, but it tells you where the function was called from (as the macros __LINE__ and __FILE__ are at the call site), which is really handy!

Rather than using some horrible macros being conditionally defined based on the build it'd be nice to have some conditionally defined code that uses the stack unwinding library.

What library is used? When one compiles can the compiler be told how much information to record? Obviously for a release build you just want what is needed for exception handling.

If not what is the convention? How do C++ programmers get what Python and Java programmers take for granted - verbose stack traces.

I suppose a fallback but not very elegant solution would be to create a new base from which I throw exceptions and have a macro that rethrows and appends line, file and __FUNCTION__, but this is a fallback.

I am interested in what library GCC uses and options to give to GCC to control how much info it puts in, so please share any knowledge you have on that!

1

There are 1 best solutions below

0
On

here is another option if you are using under linux.

1) design your signal handler, so any exception will be handled by your own signal handler instead of system like generating coredump file.

2) In your signal handler, using system call pstack to generate trace information as long as getting exception.

like ::system ("pstack yourpid >logfilename");