Reputation: 1197
I know the that the alternative approach is to convert the macro to inline function which will allow the gdb to step into it.
But I want to know if there is any way by which I can debug through each line of a macro definition by using gdb like any other function.
e.g. in the below code snippet.
#define print_macro printf("We're inside the macro now");\
for(int i=0; i<100; i++) \
{ \
if(i%2 == 0) \
printf("%d is even number", i); \
else \
printf("%d is odd number);\
}
int main()
{
print_macro;
return 0;
}
In the gdb prompt can we break in main and then step into print_macro
and go through each line of it's definition one by one by using next
Upvotes: 2
Views: 7607
Reputation: 2298
Check out the gdb commands:
gdb> macro expand *expression using macros*
gdb> info macro *macro name*
Depending on you g++ version, you may need to add -ggdb3 to the compile command.
If a macro is defined multiple times, info macro
will by default show the one that applies at the current location. info macro -all ...
lists the possible alternatives.
Upvotes: 2
Reputation: 2260
The debugging difficulty is one of the reasons why macros should be avoided. No, you cannot debug macro commands line by line, you can not set breakpoint in macro, you can not see variables values in the macro etc. The reasons for this are at least two:
Technical. The compiler doesn't know anything about macros expansion at all. All macros are expanded by the preprocessor before the compiler is called. The compiler will not be able to add debugging information for addressing macro lines, compiler doesn't have it! So debugger can only assume how exactly the preprocessor performs macro expansion.
Logical. The output C++ code command does not necessarily correspond to one line of (one) macro. Structurally and syntactically, the macro code may absolutely not be like C++ code. Such line by line macro debugging seems logical only for simple examples like yours where the resulting C++ code is easily viewed (easily for you, not for debugger!). But consider a more convoluted example. At what line debugger should indicate in this example? I think ASSIGN(VAR(INT, i), 10);
the only logical option.
#define INT int
#define VAR(TYPE, NAME) TYPE NAME
#define ASSIGN(V, VAL) V = VAL
ASSIGN(VAR(INT, i), 10);
You cannot debug macros as С++ code since they are not directly С++ code! However, you can expand a macro for debugging as advised. If you need flexibility like macros but without debugging problems, use template functions.
Upvotes: 1
Reputation: 11008
You can't step through macros but you can use the -E
flag to see what the macros expand to:
g++ main.cpp -E | less
Upvotes: 0