#490 – Using the DEBUG Conditional Compilation Symbol

By default, Visual Studio creates a Debug build configuration in which the Define DEBUG constant option is checked.

You can check to see if this constant (or “conditional compilation symbol”) is defined in your code, using the #if directive.

        public void Bark()
        {
#if DEBUG
            Console.WriteLine("DEBUG INFO: Entering Dog.Bark() [{0}]", Name);
#endif

            Console.WriteLine("{0} says woof", Name);

#if DEBUG
            Console.WriteLine("DEBUG INFO: Exiting Dog.Bark() [{0}]", Name);
#endif
        }

Code between the #if DEBUG and matching #endif will be compiled only if the DEBUG compilation symbol has been defined.  By default, this will be true for the Debug build configuration, but not the Release build configuration.

When we select the Debug build configuration and re-build, we see the following output:

When we select the Release build configuration, where the DEBUG symbol is no longer defined, we see the following output:

Advertisements

#489 – Debug and Release Configurations Are Created Automatically

When you create a new project, two build configurations are created for you automatically–Debug and Release.  The Debug configuration is meant to be used for debugging your application and the Release configuration is meant to be the one that you build with when releasing your application.

The Debug configuration

  • Defines the DEBUG constant (which you can use in your code to conditionally compile code only when debugging)
  • Does not optimize the code (to make stepping through the code in the debugger easier)
  • Builds output in \bin\Debug directory, rather than \bin\Release
  • Outputs full debug info, so that the appropriate source code lines can be located when debugging

#112 – Conditionally Compiling Code in Debug Builds

By default, the C# project wizard sets up every project to have two different build configurations–Debug and Release.

Debug builds (as compared with Release builds):

  • Create executables in \bin\Debug directory
  • Do not optimize code
  • Define the DEBUG symbol
  • Write out full debug info

You build your projects in the Debug configuration during development, for the best debugging experience.  Then, when your program is ready to ship, you build the Release configuration and ship that version.

You may want to include certain code in your program that you use only for debugging purposes–so you include it in only the Debug build.  You do this using the #if directive, checking the DEBUG variable.

 static void Main(string[] args)
 {
#if DEBUG
     DoSomeLogging();   // Only do this in Debug build
#endif
    uint x = 0x1234;
    x &= 0x0020;
 }

Code within the #if/#endif directives will not be included in the release build.