Search code examples
c++debuggingc-preprocessorcompiler-flags

C++ adding Debugging code that only runs when Debugging


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++.


Solution

  • This question could mean 1 of 2 things:

    1. Code that only runs based on the build configuration (e.g. Release vs. Debug)
    2. Code that only runs when the debugger is attached

    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:

    bool gDebug = false;
    

    And when I have attached to the code with my debugger, break in the code and override gDebug with true via the Watch window. Then you can add code that runs conditionally if this is set is true:

    if (gDebug)
    {
        // Debugger is attached, so run this code
        // ...
    }
    

    Registry key

    Define a DWORD registry value which is initialised to 0, but you can override to 1 via 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.