As the question explains: I would like to add some debugging code that only runs when the program is attached to the debugger. I would imagine that this flag or pre-processor variable would be different for every compiler…
In my case I am using Microsoft Visual Studio 2010 with C++.
I also use Eclipse on another computer at home running Ubuntu 10.4 and again in C++.
This question could mean 1 of 2 things:
Based on build configuration
This can be solved by using the pre-processor macro relevant to your compiler (e.g. _DEBUG for the Win32 CRT).
Based on whether debugger is attached
This can be solved in several different ways.
Global boolean variable
One way I find is to define a global boolean variable which is initialised to
false, like this:And when I have attached to the code with my debugger, break in the code and override
gDebugwithtruevia the Watch window. Then you can add code that runs conditionally if this is set is true:Registry key
Define a
DWORDregistry value which is initialised to0, but you can override to1via the registry editor.You then make your debug code conditional on this registry value being set to
1.This may be a better alternative as you can control this value externally without have to break in your debugger to set a global variable at the appropriate time.