0

I am currently developing a program that I intend to be portable. I have access to both Windows and macOS, and I would like to be able to debug easily on both. When error handling, I want to have debug breaks in there to make it easy(__debugbreak() for MSVC). Since I intend to develop and test on multiple platforms, I would like to make a macro to do something like this:

#define DEBUG_BREAK #ifdef DEBUG\
    #if _MSC_VER                \
        __debugbreak();         \
    #elif __GNUC__              \
        __builtin_trap();       \
    #endif                      \
#endif

So I can write DEBUG_BREAK anywhere I want to break code when debugging on any platform. When I use this macro, I get the error '#' not expected here.

I found two somewhat related questions:

  1. How to use #if inside #define in the C preprocessor?
  2. C preprocessor #if expression

But neither of them answered my question, as they were trying to accomplish different things.

So my question is: How can I have preprocessor if statements inside of a macro if that is allowed? If it isn't possible, what can I do to get the same functionality this broken DEBUG_BREAK macro is trying to do?

Note: DEBUG is defined when compiling for debugging; it is not defined when compiling for release.

coopikoop
  • 15
  • 4
  • The preprocessor only runs once, so once it's replaced `DEBUG_BREAK` with the code you've written it stops there and now you are left with unprocessed preprocessing commands in your code. – NathanOliver Nov 28 '22 at 19:13

1 Answers1

6

You can't. But you can do this:

#ifdef DEBUG
    #ifdef _MSC_VER
        #define DEBUG_BREAK __debugbreak();
    #else
        #define DEBUG_BREAK __builtin_trap();
    #endif
#else
    #define DEBUG_BREAK /*nothing*/
#endif
user253751
  • 57,427
  • 7
  • 48
  • 90