我正在尝试自学 OpenCL,而且我才刚刚开始。现在我正在阅读这本书 OpenCL In Action。 我在我的文件中复制了一个测试代码,但我无法掌握如何运行该代码。也就是说,我该如何编译它? 在 C 中,我们使用 gcc 来获取我们可以运行的文件。 但是在使用 C 的 OpenCL 中,我被卡住了。
找不到任何地方有清晰的信息和实际编译背后的逻辑。
这是我要运行的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
int main() {
cl_platform_id *platforms;
cl_uint num_platforms;
cl_int i, err, platform_index = -1;
char* ext_data;
size_t ext_size;
const char icd_ext[] = "cl_khr_icd";
err = clGetPlatformIDs(1, NULL, &num_platforms);
if(err < 0) {
perror("Couldn't find any platforms.");
exit(1);
}
platforms = (cl_platform_id*)
malloc(sizeof(cl_platform_id) * num_platforms);
clGetPlatformIDs(num_platforms, platforms, NULL);
for(i=0; i<num_platforms; i++) {
err = clGetPlatformInfo(platforms[i],
CL_PLATFORM_EXTENSIONS, 0, NULL, &ext_size);
if(err < 0) {
perror("Couldn't read extension data.");
exit(1);
}
ext_data = (char*)malloc(ext_size);
clGetPlatformInfo(platforms[i],CL_PLATFORM_EXTENSIONS,ext_size,ext_data,NULL);
printf("Platform %d supports extensions: %s\n",i, ext_data);
if(strstr(ext_data, icd_ext) != NULL) {
free(ext_data);
platform_index = i;
break;
}
free(ext_data);
}
if(platform_index > -1)
printf("Platform %d supports the %s extension.\n",platform_index,icd_ext);
else
printf("No platforms support the %s extension.\n", icd_ext);
free(platforms);
return 0;
}
最佳答案
正如上面 UnholySheep 在评论中所指出的,我们需要将 C 代码链接到 OpenCL 库。
假设 C 源文件名为 test.c ,在 64 位系统上编译它的命令将是;
gcc test.c -lOpenCL -L$AMDAPPSDKROOT/lib/x86_64
更多可以引用AMD提供的手册: AMD_OpenCL_Programming_User_Guide
用户指南的第 3.1.2 节回答了这个问题的具体部分,如下所示,
在 Linux 上编译
To compile OpenCL applications on Linux, gcc or the Intel C compiler must be installed. There are two major steps: compiling and linking.
Compile all the C++ files (Template.cpp), and get the object files. For 32-bit object files on a 32-bit system, or 64-bit object files on 64-bit system:
g++ -o Template.o -c Template.cpp -I$AMDAPPSDKROOT/include
For building 32-bit object files on a 64-bit system:
g++ -o Template.o -c Template.cpp -I$AMDAPPSDKROOT/includeLink all the object files generated in the previous step to the OpenCL library and create an executable.
For linking to a 64-bit library:
g++ -o Template Template.o -lOpenCL -L$AMDAPPSDKROOT/lib/x86_64
For linking to a 32-bit library:
g++ -o Template Template.o -lOpenCL -L$AMDAPPSDKROOT/lib/x86
关于c - 如何在 Linux (ubuntu 16.04) 上运行 OpenCL 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42828329/