在 #define 宏中控制条件 Openmp

control conditional Openmp in #define macro

我想使用 #define 标志来控制是否使用 openmp。由于 #pragma 不能不在 #define 内,所以我尝试了

#define USE_OPENMP  // Toggle this on/off

#ifdef USE_OPENMP
    #define OMP_FOR(n)   __pragma("omp parallel for if(n>10)") 
#else
    #define OMP_FOR(n)   // do nothing        
#endif

然后在我的代码中我可以:

int size_of_the_loop = 11;
OMP_FOR(size_of_the_loop) // activate openmp if(n>10)
for(){
    //do stuff
}

我不熟悉 #define 相关的东西,想知道是否可以实现这个?谢谢。

Microsoft 编译器将定义 _OPENMP macro when the /openmp 编译器选项设置。为了您的目的,您可以以这种形式使用它:

#ifdef _OPENMP
    #include <omp.h>     // This line won't add the library if you don't compile with -fopenmp option.
    #ifdef _MSC_VER
         // For Microsoft compiler
         #define OMP_FOR(n) __pragma(omp parallel for if(n>10)) 
    #else  // assuming "__GNUC__" is defined
         // For GCC compiler
         #define OMP_FOR(n) _Pragma("omp parallel for if(n>10)")
    #endif
#else
    #define omp_get_thread_num() 0
    #define OMP_FOR(n)
#endif

现在您可以像这样使用 OMP_FOR(n)

int main() {
    int n=11;

    OMP_FOR(n)
    for(int i=0; i<4; i++)
        printf("Thread %d\n",omp_get_thread_num());
}

您必须使用以下命令编译代码:

cl /fopenmp file.c

或者,如果您使用的是 GCC,

gcc -fopenmp file.c -o exe

n>10 的输出:

Thread 2
Thread 0
Thread 1
Thread 3

n<10 的输出:

Thread 0
Thread 0
Thread 0
Thread 0

OpenMP 编译器必须根据 OpenMP 规范定义 _OPENMP,如评论之一所示。

由于 OpenMP 指令基于编译指示,如果编译器不支持 OpenMP 或未通过编译器开关启用 OpenMP,则编译器应忽略 OpenMP 指令。因此,除非您依赖 OpenMP 运行时 API 调用,否则通常不需要在大多数代码中使用 _OPENMP

编辑:OpenMP 架构审查委员会在 https://github.com/OpenMP/sources 发布了一个存根库作为源代码。此存根库可用于提供 OpenMP API 运行时库符号并获取 "no op" 存根,这些存根可以正确实现 single-threaded 执行的语义。