How to determine if there is a debugger attached in C ++?

I created a macro,

#define DEBUG_BREAK(a) if (a) __asm int 3; 

But the problem is that in the absence of a debugger, the program will not work correctly.

So I need to know if there is a debugger. If there is a debugger, the application should call int 3 . Otherwise it should not be.

How can i do this?

+6
source share
2 answers

You can use CheckRemoteDebuggerPresent or IsDebuggerPresent - and no, CheckRemoteDebuggerPresent does not necessarily mean that the debugger is running on another computer, it just has a debugging system that can work with breakpoints, etc. (when using the remote debugger, there is a small process on the target system, too, where it comes from).

Edit: And at that moment I would DEFINITELY offer some form of function, not a macro.

+4
source

For what you want to do, it would be better if you used the proper open kernel32.dll DebugBreak function. Mostly along the lines

 #define DEBUG_BREAK(a) if(a) if (IsDebuggerPresent()) DebugBreak() 

or instead of executing the __asm int 3 procedure, use the built-in VC __debugbreak , ie:

 #define DEBUG_BREAK(a) if(a) if (IsDebuggerPresent()) __debugbreak() 

The latter matters (compared to int 3 ) when compiling with /clr , as indicated in the documentation . Of course, the inside was not always there, so it depends on your version of VS / VC (which you do not declare).

In both cases, you will need at least windows.h for IsDebuggerPresent() .


Nevertheless, this is the exact reason why you will have a debug and release assembly and build them conditionally. Keep in mind that the optimizer can distort the results in the debugger, despite your efforts to carefully set breakpoints in your code. The reason is that some lines in your source code will no longer be presented or will be changed in a deterministic way. Therefore, using the same configuration for both does not make much sense. So what I'm saying is to use something line by line:

 #ifdef _DEBUG # define DEBUG_BREAK(a) if(a) __debugbreak() #else # define DEBUG_BREAK(a) do {} while(0) #endif 
+6
source

Source: https://habr.com/ru/post/945552/


All Articles