GCC _Pragma 运算符中的预处理器标记粘贴
我正在尝试做类似于另一个问题的事情,即有条件地在我的程序中包含 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());
}
}
不幸的是,这不起作用。编译器抱怨:
错误:
_Pragma
采用带括号的字符串文字
如果我使用以下形式,它会起作用:
#define LIB_PRAGMA_OMP(x) _Pragma(#x)
…
LIB_PRAGMA_OMP(omp parallel) …
但是,我真的很想避免这种冗余。 如何将(字符串化的)标记正确粘贴到 _Pragma
运算符内?
I’m trying to do something similar to another question, namely, conditionally include OpenMP pragmas in my program. However, I want to go one step further and avoid that the user needs to specify omp
every time they use the pragma. In other words, I want the following code to compile:
#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());
}
}
Unfortunately, this doesn’t work. The compiler complains:
error:
_Pragma
takes a parenthesized string literal
If I use the following form, it works, though:
#define LIB_PRAGMA_OMP(x) _Pragma(#x)
…
LIB_PRAGMA_OMP(omp parallel) …
However, I’d really like to avoid this redundancy. How can I paste the (stringified) tokens correctly inside the _Pragma
operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过多次尝试和错误,事实证明最简单的解决方案有效:
使用
-DOPENMP
,我得到:没有它,什么也没有。
After much trial and error, it turns out that the simplest solution works:
With
-DOPENMP
, I get:And without it, nothing.
如果您愿意的话,也可以。我更喜欢它,因为它最大限度地减少了辅助函数所做的工作量。
Also works, if you prefer that. I like it better because it minimizes the amount of work this helper function does.