__debugbreak statement not triggering breakpoint
In my visual C++ code I have introduced a __debugbreak statement for triggering a breakpoint. I have compiled the project with /CLR option. But it does not trigger a breakpoint during execution. Why does this happen? Please help before I shoot myself. This in on 64 bit executable.
Edit: I tried with DebugBreak() statement now and it is now hanging forever, not sure at which statement. The dll is used by a server program, which I'm accessing from a client on a different machine. Is this what is causing the problem? Should I be running it from the server machine itself? I expected it to atleast report a message about a breakpoint being triggered, even if it could not successfully launch the debugger session on the client machine开发者_如何学JAVA. The .pdb file is avaialable on the server at the same location as the dll.
Update: I just tried ran the client program on the server machine itself, but still the DebugBreak() causes an infinite hanging. The debugger session does not get launched.
Why cannot you use F9 (Breakpoint) from within the debugger?
A DebugBreak();
should work however.
If DLL/EXE cannot be loaded directly, you may "Attach To Process" from "Debug" menu (Hope you are using Visual Studio).
I use this code in C#, maybe you can adapt it for C++
#if DEBUG
var endTime = DateTime.Now.AddSeconds(30);
while (!System.Diagnostics.Debugger.IsAttached && DateTime.Now < endTime)
System.Threading.Thread.Sleep(10);
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
#endif
While @user1772138's answer is correct for C♯, for modern C++, a more appropriate solution is:
#if DEBUG && (__WIN32 || __WIN64)
#include <chrono>
#include <ctime>
#include <thread>
#include <windows.h>
#include <debugapi.h>
using namespace std::chrono_literals;
using std::chrono::system_clock;
#endif // DEBUG
Then, in your main:
int main(int argc, char *argv[]) {
#if DEBUG && (__WIN32 || __WIN64)
auto endTime = system_clock::now() + 30s;
while (!::IsDebuggerPresent() && system_clock::now() < endTime) {
std::this_thread::sleep_for(10s);
}
if (::IsDebuggerPresent()) {
__debugbreak();
}
#endif // DEBUG
// Main code goes here
Even if __debugbreak
doesn't work—it's the equivalent of the C♯ System.Diagnostics.Debugger.Break
—the first part waits 30 seconds before the program starts and if you have successfully attached the debugger in this time, you won't need to call the __debugbreak
. You just put a break in the program which spawns your program, and then when you reach that point, step beyond it, and attach to the process in Visual Studio Debug->Attach to Process…
EDIT: Added a check to make sure this is running on Windows; under Linux the code would be different, but the op was asking for a Windows solution.
精彩评论