我正在尝试将OpenMP与另一种发出C代码的语言(C代码生成器)进行交互.从我的角度来看(我不是另一种语言的设计者),通过调用C函数或类似函数的宏而不是直接使用#pragma或_Pragma来实现这一点是最简单的.我对C预处理器没有太多经验,但是我在维基百科上找到了一个简单的例子,以不令人满意的方式工作.这是原始的C示例:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int th_id, nthreads;
#pragma omp parallel private(th_id)
{
th_id = omp_get_thread_num();
printf("Hello World from thread %d\n", th_id);
#pragma omp barrier
if ( th_id == 0 ) {
nthreads = omp_get_num_threads();
printf("There are %d threads\n",nthreads);
}
}
return EXIT_SUCCESS;
}
现在我在这里创建一个宏(pragma_omp_parallel_private)来做我想要的事情:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define STR(x) #x
#define STRINGIFY(x) STR(x)
#define omp_par_pri STRINGIFY(omp parallel private)
char omp_test[] = omp_par_pri;
#define pragma_omp_parallel_private(thread_id) \
_Pragma(STRINGIFY(omp parallel private ## (thread_id)))
int main (int argc, char *argv[]) {
int th_id, nthreads;
// #pragma omp parallel private(th_id)
pragma_omp_parallel_private(th_id)
{
th_id = omp_get_thread_num();
printf("Hello World from thread %d\n", th_id);
#pragma omp barrier
if ( th_id == 0 ) {
nthreads = omp_get_num_threads();
printf("There are %d threads\n",nthreads);
}
}
return EXIT_SUCCESS;
}
预处理器将发出错误,但如果我实际编译预处理的代码,它将按预期工作.有没有更合法的方法来实现这一点(更不用说在大多数构建管道中不会导致构建错误的方法)?
$gcc -E -fopenmp wikiHello.c > wikiHello_pp.c
wikiHello.c:11:34: error: pasting "private" and "(" does not give a valid preprocessing token
_Pragma(STRINGIFY(omp parallel private ## (thread_id)))
^
wikiHello.c:17:3: note: in expansion of macro ‘pragma_omp_parallel_private’
pragma_omp_parallel_private(th_id)
^
$gcc -fopenmp wikiHello_pp.c
$./a.exe
Hello World from thread 3
Hello World from thread 6
Hello World from thread 4
Hello World from thread 7
Hello World from thread 1
Hello World from thread 5
Hello World from thread 2
Hello World from thread 0
There are 8 threads
最佳答案 在将它转换为字符串文字之前,我会将该pragma连接起来.像这样的东西:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define STR(x) #x
#define STRINGIFY(x) STR(x)
#define CONCATENATE(X,Y) X ( Y )
#define pragma_omp_parallel_private(x) \
_Pragma( STRINGIFY( CONCATENATE(omp parallel private,x) ) )
int main (int argc, char *argv[]) {
int th_id, nthreads;
// #pragma omp parallel private(th_id)
pragma_omp_parallel_private(th_id)
{
th_id = omp_get_thread_num();
printf("Hello World from thread %d\n", th_id);
#pragma omp barrier
if ( th_id == 0 ) {
nthreads = omp_get_num_threads();
printf("There are %d threads\n",nthreads);
}
}
return EXIT_SUCCESS;
}