Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ – How to use preprocessor if statements(#if, #elif, #endif) inside a macro?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading