在GCC的_Pragma运算符中粘贴预处理程序令牌

Kon*_*lph 6 c++ gcc c-preprocessor

我正在尝试做一些类似于另一个问题的事情,即在我的程序中有条件地包含OpenMP pragma.但是,我想更进一步,避免用户omp每次使用pragma时都需要指定.换句话说,我想要编译以下代码:

#include <cstdio>
#include <omp.h>

#ifdef _OPENMP
#   define LIB_PRAGMA_OMP(x) _Pragma("omp " #x)
#else
#   define LIB_PRAGMA_OMP(x)
#endif

int main() {
    LIB_PRAGMA_OMP(parallel) {
        std::printf("Hello from thread %d\n", omp_get_thread_num());
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用.编译器抱怨:

错误:_Pragma采用带括号的字符串文字

如果我使用以下表格,它可以工作,但是:

#define LIB_PRAGMA_OMP(x) _Pragma(#x)

…

LIB_PRAGMA_OMP(omp parallel) …
Run Code Online (Sandbox Code Playgroud)

但是,我真的想避免这种冗余.如何在_Pragma操作符内正确粘贴(字符串化)标记?

Dav*_*rtz 9

经过多次试验和错误,事实证明最简单的解决方案是有效的:

#ifdef _OPENMP
#   define LIB_PRAGMA_OMP(x)  DO_PRAGMA(omp x)
#   define DO_PRAGMA(x) _Pragma ( #x )
#else
#   define LIB_PRAGMA_OMP(x)
#endif
Run Code Online (Sandbox Code Playgroud)

随着-DOPENMP,我得到:

# 12 "test_op.cpp"
#pragma omp parallel
# 12 "test_op.cpp"
Run Code Online (Sandbox Code Playgroud)

没有它,没有.

  • 如果它是如此明显,为什么它像我尝试的第20件事?:) (3认同)