In MSVC, DebugBreak() or __debugbreak cause a debugger to break. On x86 it is equivalent to writing \"_asm int 3\", on x64 it is something different. When compiling with gcc
What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform.
Something like:
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak()
#else
...
#endif
This would be expanded by the preprocessor the correct debugger break instruction based on the platform where the code is compiled. This way you always use DEBUG_BREAK
in your code.
I just added a module to portable-snippets (a collection of public domain snippets of portable code) to do this. It's not 100% portable, but it should be pretty robust:
__builtin_debugtrap
for some versions of clang (identified with __has_builtin(__builtin_debugtrap)
)__debugbreak
__breakpoint(42)
int3
.inst 0xde01
.inst 0xd4200000
.inst 0xe7f001f0
bpt
__builtin_trap
signal.h
and
defined(SIGTRAP)
(i.e., POSIX), raise(SIGTRAP)
raise(SIGABRT)
In the future the module in portable-snippets may expand to include other logic and I'll probably forget to update this answer, so you should look there for updates. It's public domain (CC0), so feel free to steal the code.
Instead of using 'normal' debug breaks, why not use one of the following, like a divide by zero:
int iCrash = 13 / 0;
or dereference a NULL pointer:
BYTE bCrash = *(BYTE *)(NULL);
At least this is portable accross many platforms/architectures.
In many debuggers you can specify what action you want to perform on what exceptions so you can act accordingly when one of the above is hit (like pause execution, ala an "int 3" instruction) and an exception is generated.
GCC has a builtin function named __builtin_trap
which you can see here, however it is assumed that code execution halts once this is reached.
you should ensure that the __builtin_trap()
call is conditional, otherwise no code will be emitted after it.
this post fueled by all of 5 minutes of testing, YMMV.