Is there a way to define a preprocessor macro that includes preprocessor directives?

There are a few loops I would like to direct the compiler to unroll with code like below. It is quite long and I’d rather not copy-paste.

Can #define statements define preprocessor macros?

I tried this:

#define foo \
    #ifdef __GNUC__                                             \
        #if __GNUC__ >= 8                                       \
            #pragma GCC unroll 128                              \
            #pragma GCC ivdep                                   \
        #endif                                                  \
    #endif                                                      \
    #ifdef __clang__                                            \
        #pragma clang loop vectorize(enable) interleave(enable) \
    #endif     

but when I use foo in the code cpp shows that it expands invalidly as:

 #ifdef 4 #if 4 >= 8 #pragma GCC unroll 128 #pragma GCC ivdep #endif #endif #ifdef __clang__ #pragma clang loop vectorize(enable) interleave(enable) #endif
 #ifdef 4 #if 4 >= 8 #pragma GCC unroll 128 #pragma GCC ivdep #endif #endif #ifdef __clang__ #pragma clang loop vectorize(enable) interleave(enable) #endif

>Solution :

You cannot define preprocessing directives the way you show in the question.

Yet you may be able to use the _Pragma operator for your purpose:

#if defined __GNUC__ && __GNUC__ >= 8
    #define foo _Pragma("GCC unroll 128") _Pragma("GCC ivdep")
#elif defined __clang__
    #define foo _Pragma("clang loop vectorize(enable) interleave(enable)")
#else
    #define foo
#endif

Leave a Reply