Tuesday, December 25, 2012

examine macro definition in gdb

When debugging a c++ application, I used to refer to source code to find out the actual definition of a macro. If the macro is not a simple one, I had to perform the expansion on a paper or use the 'gcc -E' command to find out what's the actual result. This is a tedious task. The gdb macro command helps examine the macro value, as long as the application under debugging contains information about preprocessor macros. This can be satisfied by passing -g3 option to the gcc compiler. As an example, we need to debug the application below
 1 #define FOO foo_value
 2 #define STR(val) "STR of "#val
 3 #define VAL STR(FOO)
 4 
 5 int main(int argc, const char *argv[])
 6 {
 7     const char* t = VAL;
 8 #undef VAL
 9 #define VAL "test" // define VAL to a different value 
10     const char* t2 = VAL;
11 
12     return 0;
13 }
We compile the code with gcc -g3 command, and debug it in gdb. Then we can examine the actual value of VAL macro with macro exp command.
(gdb) macro exp VAL  // run when break on line 7
expands to: "STR of ""FOO"
....
(gdb) macro exp VAL  // run when break on line 10
expands to: "test"
It's worthy of note that the macro expansion is context awareness in gdb, so we can get different value when the application breaks on line 7 and 10.

4 comments:

Unknown said...

Website Hosting GreenWebby delivers turnkey web hosting solutions that are tailored to your specific needs. Our deep experience as a hosting company, has helped us create scalable hosting solutions that promise exceptional performance and unmatched value. Our web hosting service is coupled with world-class technical support and powers more than 6 million websites worldwide.

Unknown said...

nice post, keep up with this interesting work. It really is good to know that this topic is being covered also on this web site so cheers for taking time to discuss this!

Best UI/UX Design Services

Unknown said...

I am unable to read articles online very often, but I’m glad I did today.This is very well written and your points are well-expressed.Please, don’t ever stop writing.


Product Development Company in UAE

Anonymous said...


Hi.
I appreciate your kind words about the post! Your encouragement means a lot to me, and it motivates me to continue producing engaging and interesting. Here is sharing some AlterY Training information may be its helpful to you.
AlterYX Training