Reputation: 41805
I have created a macro,
#define DEBUG_BREAK(a) if (a) __asm int 3;
But the problem is if there is no debugger attached, the program would run incorrectly.
So I need to know whether there is a debugger attached. If there's a debugger, the app should call int 3
. Otherwise, it should not.
How could i do this?
Upvotes: 7
Views: 9857
Reputation: 21279
For what you want to do, it would be better if you'd use the proper exposed kernel32.dll
function DebugBreak
. Basically along the lines of
#define DEBUG_BREAK(a) if(a) if (IsDebuggerPresent()) DebugBreak()
or instead of doing the __asm int 3
routine, use the VC-supplied intrinsic __debugbreak
, i.e.:
#define DEBUG_BREAK(a) if(a) if (IsDebuggerPresent()) __debugbreak()
The latter makes a difference (compared to int 3
) when compiling with /clr
as pointed out in the documentation. Of course the intrinsic hasn't always been there, so depends on your VS/VC version (which you don't state).
In both cases you need at least windows.h
included for IsDebuggerPresent()
.
However, that's the exact reason you would have a debug and release build and build those conditionally. Keep in mind that the optimizer can garble the results in the debugger despite your efforts to carefully place the breakpoints in code. The reason is simply that some lines in your source code won't be represented anymore or will have changed in a deterministic manner. So using one configuration for both doesn't make a lot of sense. So what I'm saying is to use something along the lines of:
#ifdef _DEBUG
# define DEBUG_BREAK(a) if(a) __debugbreak()
#else
# define DEBUG_BREAK(a) do {} while(0)
#endif
Upvotes: 7
Reputation: 129374
You can use CheckRemoteDebuggerPresent
or IsDebuggerPresent
- and no, CheckRemoteDebuggerPresent
doesn't necessarily mean that the debugger runs on a different machine, just that there is a debugging process in the system that can deal with breakpoints etc (when using a Remote Debugger, there is a small process on the target system too, which is where it comes from).
Edit: And at this point I would DEFINITELY suggest some form of function, rather than a macro.
Upvotes: 5