Code_Complete
Code_Complete

Reputation: 115

How to write a debug macro to print all the arguments of function (strace style) in C++?

Given any function like

void f(int a, int b, char c) {


---macro here----

}

now DBG_ARGS should have output like
f(a = 1, b = 2, c = A)

Can we use VA_LIST, #x and __FUNCTION__ to accomplish this?

Upvotes: 1

Views: 270

Answers (1)

abligh
abligh

Reputation: 25189

I don't think you can do this with a straight macro alone in the general case, but you could do it using a call to another function.

If you look at the manual page for backtrace, you will find a glibc specific routine to dump the stack. If you call another function Y from your current function X, and that function dumps the stack, then the second line of the stack dump will be the arguments to function X (make sure the compiler does not inline the function).

Sadly this method isn't particularly portable. OS-X and Linux have different backtrace type implementations, and I'm sure Windows does too.

The va_list-esque macros only work with variadic functions. The example you gave is not a variadic function. I'm not exactly aware what VA_LIST (upper case) does (perhaps that's compiler specific), but google suggests it's pretty much the same.

Upvotes: 1

Related Questions