如何在 Linux (ubuntu 16.04) 上 运行 OpenCL 程序?

How to run OpenCL programs on Linux (ubuntu 16.04)?

我正在尝试自学 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 在评论中指出的那样,我们需要 link 针对 OpenCL 库的 C 代码。

假设 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.

  1. 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/include

  2. Link 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

我的 Dell Inspiron 上有一个 Intel Kaby Lake GT2 GPU,它运行 Ubuntu 18.04。安装 OpenCL 后,开发的下一步是获取一个简单的代码示例和 运行.

我先把概述的代码here放在本地目录下,然后使用g++

进行编译
g++ *.cpp -lOpenCL

你的里程会有所不同,你可能还需要包含头文件