April 26th, 2018

How can I have my program execute some code only if run from the Visual Studio debugger?

A customer wanted their program to operate in a special mode if it is being debugged from inside the Visual Studio development environment. Say, if being run from Visual Studio via the “Start with debugging” menu, it should display a diagnostic window that contains additional information.

You should think twice before you do this.

Sure. you could use a function like Is­Debugger­Present to sniff whether your process is being debugged, and if so turn on additional features suitable for debugging. But you also run into the risk of having a bug that occurs only when your program isn’t being debugged.¹ And everybody hates those types of bugs.

You should have a command line switch that enables the diagnostic window. You can configure Visual Studio so that when you run the program under Visual Studio, it gets the command line switch. That way, when you have a bug that goes away when the diagnostic window is open, you can remove the command line switch and debug it. (It also means that when run outside Visual Studio, you can give the special command line switch and get the diagnostics window even though no debugger is running.)

As a compromise, you could enable the diagnostic window by default if Is­Debugger­Present reports that there is a debugger, but make sure you have a command line switch to override that call and disable the diagnostic window so that you can debug the bugs that occur only when the diagnostic window is not present.

¹ Maybe the diagnostic window calls some functions that have side effects which are masking a bug in the program. For example, the diagnostic window might perform extra logging, which introduces a change in timing that masks a race condition.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.