Tyler
Tyler

Reputation: 28874

Is there a good general method for debugging C++ macros?

In general, I occasionally have a chain of nested macros with a few preprocessor conditional elements in their definitions. These can be painful to debug since it's hard to directly see the actual code being executed.

A while ago I vaguely remember finding a compiler (gcc) flag to expand them, but I had trouble getting this to work in practice.

Upvotes: 13

Views: 2867

Answers (7)

Jacob
Jacob

Reputation:

GCC and compatible compilers use the -E option to output the preprocessed source to standard out.

gcc -E foo.cpp

Sun Studio also supports this flag:

CC -E foo.cpp

But even better is -xdumpmacros. You can find more information in Suns' docs.

Upvotes: 0

archbishop
archbishop

Reputation: 1127

gcc -save-temps will write out a .i (or .ii file for C++) which is the output of the C preprocessor, before it gets handed to the compiler. This can often be enlightening.

Upvotes: 1

Robert Gould
Robert Gould

Reputation: 69893

You should probably start moving away form Macros and start using inline and templates.

Macros are an old tool, the right tool sometimes. As a last resort remember printf is your friend (and actually printf isn't that bad a friend when your doing multithreaded stuff)

Upvotes: 2

Joe Schneider
Joe Schneider

Reputation: 9339

This might not be applicable in your situation, but macros really do hamper debugging and often are overused and avoidable.

Can you replace them with inline functions or otherwise get rid of them all together?

Upvotes: 5

Tim Lovell-Smith
Tim Lovell-Smith

Reputation:

For MSVC users, you can right-click on the file/project, view the settings and change the file properties to output preprocessed source (which typically in the obj directory).

Upvotes: 8

Nemanja Trifunovic
Nemanja Trifunovic

Reputation: 24561

Debug the dissasembly with the symbols loaded.

Upvotes: 1

dvorak
dvorak

Reputation: 32169

gcc -E will output the preprocessed source to stdout.

Upvotes: 14

Related Questions