clinuxopenclopencl-c

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


I am trying to learn OpenCL on my own and I have just started off. Now I am reading this book OpenCL In Action. I have copied a test code in my file but I am not able to get a hang of how to run that code. That is, how do I compile it ? In C, we use gcc to get out file which we can run. But here in OpenCL with C, I am stuck.

Couldn't find any place with clear info and logic behind how to actually compile.

here's the code that I wanna run:

#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;
}

Solution

  • As pointed by UnholySheep above in comments we need to link the C code against the OpenCL Library.

    Assuming the C source file is named test.c , command to compile it on a 64-bit system would be;

    gcc test.c -lOpenCL -L$AMDAPPSDKROOT/lib/x86_64

    More can be found from the manual provided by AMD: AMD_OpenCL_Programming_User_Guide

    Part specific to this questions is answered in Section 3.1.2 of the user guide as follows,

    Compiling on 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