使用OpenCL编程时,kernel写成一个单独的文件或者将文件内容保存在一个string中。可以使用clBuildProgram对kernel进行编译链接(compiles & links),如果失败,可以使用clGetProgramBuildInfo获取OpenCL编译器对kernel的编译信息。
1.clBuildProgram
cl_int clBuildProgram (
cl_program program, //program
cl_uint num_devices, //the number of device
const cl_device_id *device_list, //devices id
const char *options, //the option of compiler
void (CL_CALLBACK *pfn_notify)(cl_program program, void *user_data), //the callback function
void *user_data) //the data of callback function
)
2.clGetProgramBuildInfo
cl_int clGetProgramBuildInfo (
cl_program program, //program
cl_device_id device, //the id of device
cl_program_build_info param_name,
size_t param_value_size,
void *param_value,
size_t *param_value_size_ret
)
3.代码实例(获取编译器对kernel的编译信息)
3.1 kernel(build_info_kernel.cl)
1 __kernel void good(__global float *a, 2 __global float *b, 3 __global float *c) { 4 5 *c = *a + *b; 6 } 7 8 __kernel void good(__global float *a, 9 __global float *b, 10 __global float *c) { 11 __local int var=3; 12 int size=get_local_sze(0); 13 *c = *a + *b; 14 }
3.2 tool.h
1 #ifndef TOOLH 2 #define TOOLH 3 #include <CL/cl.h> 4 #include <string.h> 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <iostream> 8 #include <string> 9 #include <fstream> 10 using namespace std; 11 12 /** convert the kernel file into a string */ 13 int convertToString(const char *filename, std::string& s); 14 15 /**Getting platforms and choose an available one.*/ 16 int getPlatform(cl_platform_id &platform); 17 18 /**Step 2:Query the platform and choose the first GPU device if has one.*/ 19 cl_device_id *getCl_device_id(cl_platform_id &platform); 20 21 /**获取编译program出错时,编译器的出错信息*/ 22 int getProgramBuildInfo(cl_program program,cl_device_id device); 23 #endif
tool.cpp
1 #include <CL/cl.h> 2 #include <string.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <iostream> 6 #include <string> 7 #include <fstream> 8 #include "tool.h" 9 using namespace std; 10 11 /** convert the kernel file into a string */ 12 int convertToString(const char *filename, std::string& s) 13 { 14 size_t size; 15 char* str; 16 std::fstream f(filename, (std::fstream::in | std::fstream::binary)); 17 18 if(f.is_open()) 19 { 20 size_t fileSize; 21 f.seekg(0, std::fstream::end); 22 size = fileSize = (size_t)f.tellg(); 23 f.seekg(0, std::fstream::beg); 24 str = new char[size+1]; 25 if(!str) 26 { 27 f.close(); 28 return 0; 29 } 30 31 f.read(str, fileSize); 32 f.close(); 33 str[size] = '