views:

1866

answers:

4

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 (or any other standard compiler) I want to do a break into debugger, too. Is there a platform independent function or intrinsic? I saw the XCode question about that, but it doesn't seem portable enough.

Sidenote: I mainly want to implement ASSERT with that, and I understand I can use assert() for that, but I also want to write DEBUG_BREAK or something into the code.

+6  A: 

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.

smink
+1  A: 

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.

Hasturkun
A: 

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.

QAZ
I actually have a board here that will happily do a NULL pointer dereference. divide by zero may be safer.
Hasturkun
Interesting. How would continue from such exception when it hits? With int 3 the VS debugger knows how to continue, all I need is to press Go (F5), or if I want to disable the assert on that location, I can use the trick http://stackoverflow.com/questions/115237 - anything similar here?
Suma
+2  A: 

If you consider assert(x) portable enough, assert(false) seems to be the obvious portable solution to your problem.

Suma