C++ GCC中的预处理器标记粘贴&x2019;s_Pragma算子
我正在尝试做类似的事情,即在我的程序中有条件地包含OpenMP pragmas。但是,我想更进一步,避免用户每次使用pragma时都需要指定C++ GCC中的预处理器标记粘贴&x2019;s_Pragma算子,c++,gcc,c-preprocessor,C++,Gcc,C Preprocessor,我正在尝试做类似的事情,即在我的程序中有条件地包含OpenMP pragmas。但是,我想更进一步,避免用户每次使用pragma时都需要指定omp。换句话说,我希望编译以下代码: #include <cstdio> #include <omp.h> #ifdef _OPENMP # define LIB_PRAGMA_OMP(x) _Pragma("omp " #x) #else # define LIB_PRAGMA_OMP(x) #endif int ma
omp
。换句话说,我希望编译以下代码:
#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());
}
}
然而,我真的希望避免这种冗余如何在
\u Pragma
操作符中正确粘贴(字符串化)标记?经过多次尝试和错误,最简单的解决方案是:
#ifdef _OPENMP
# define LIB_PRAGMA_OMP(x) DO_PRAGMA(omp x)
# define DO_PRAGMA(x) _Pragma ( #x )
#else
# define LIB_PRAGMA_OMP(x)
#endif
使用-DOPENMP
,我得到:
# 12 "test_op.cpp"
#pragma omp parallel
# 12 "test_op.cpp"
没有它,什么也没有
#define MAKE_STRING(x) #x
#define LIB_PRAGMA_OMP(x) _Pragma(MAKE_STRING(omp x))
如果你喜欢的话,也可以。我更喜欢它,因为它最大限度地减少了这个helper函数所做的工作量。如果它是如此明显,为什么会像我尝试的第20件事一样呢?:)
#define MAKE_STRING(x) #x
#define LIB_PRAGMA_OMP(x) _Pragma(MAKE_STRING(omp x))