gpt4 book ai didi

c++ - GCC 的 _Pragma 运算符中的预处理器标记粘贴

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:19:56 24 4
gpt4 key购买 nike

我正在尝试做类似于 another question 的事情,即有条件地在我的程序中包含 OpenMP 编译指示。但是,我想更进一步,避免用户每次使用 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 main() {
LIB_PRAGMA_OMP(parallel) {
std::printf("Hello from thread %d\n", omp_get_thread_num());
}
}

不幸的是,这不起作用。编译器提示:

error: _Pragma takes a parenthesized string literal

不过,如果我使用以下形式,它会起作用:

#define LIB_PRAGMA_OMP(x) _Pragma(#x)



LIB_PRAGMA_OMP(omp parallel) …

但是,我真的很想避免这种冗余。 如何将(字符串化的)标记正确粘贴到 _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"

没有它,什么都没有。

关于c++ - GCC 的 _Pragma 运算符中的预处理器标记粘贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7608229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com