Search code examples
clinuxgccc-preprocessorpragma

How can I use macro expansion for the first identifier of a pragma?


If I wanted to define the first identifier of a pragma how would I do this?

For example, I need something like this to work as an openmp pragma:

#define FOO omp
#pragma FOO parallel

So I need this to be interpreted as:

#pragma omp parallel

I'm using GCC in Linux. From what I've read so far it looks like this isn't supported. Is there any sort of workaround?


Solution

  • Since C99 we have the _Pragma operator, that basically allows you to place the contents of #pragma everywhere, not only on a line of its own, and to have it subject to macro expansion. Something like

    #define STRINGIFY_(...) #__VA_ARGS__
    #define STRINGIFY(...) STRINGIFY_(__VA_ARGS__)
    #define FOO omp
    #define PARALLEL(...) _Pragma(STRINGIFY(FOO parallel __VA_ARGS__))
    

    and then

    PARALLEL(private(a))
    for(size_t i = 0; i < NUM; ++i)
      ....
    

    should do the trick.

    If you are just interested in using such stuff (compared to writing these macros) you could use P99 preprocessor blocks that implements things like P99_PARALLEL_FOR and P99_PARALLEL_FORALL with these kind of tricks.