文件树
![在这里插入图片描述](https://img-blog.csdnimg.cn/c433e5de57cc42ec8e699e04130fc2b4.png)
CMakeLists.txt固定部分写法
CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
PROJECT(DEMO4-15-1)
INCLUDE_DIRECTORIES(/usr/include/)
LINK_DIRECTORIES(/usr/local/lib /usr/lib/aarch64-linux-gnu/)
ADD_EXECUTABLE(demo4-15-1 src/main.c)
TARGET_LINK_LIBRARIES(demo4-15-1 -lOpenCL)
c语言文件写法
#pragma warning( disable : 4996 )
#include <stdio.h>
#include <CL/cl.h>
#include <stdlib.h>
#include <string.h>
#define FILE_PATH "../src/kernel.cl"
#define RAN_X 6
#define RAN_Y 4
char *readFile(){
FILE *file = fopen(FILE_PATH, "r");
if(file == NULL){
printf("Failed to open file.\n");
return NULL;
}
fseek(file, 0, SEEK_END);
size_t length = ftell(file);
fseek(file, 0, SEEK_SET);
char *source;
if(length == 0) {
printf("The file is empty.\n");
return NULL;
}
source = (char *)malloc(length+1);
size_t ret = fread(source, length, 1, file);
if(ret == 0){
printf("Failed to read file.\n");
free(source);
return NULL;
}
fclose(file);
source[length] = '\0';
return source;
}
void cleanUp(cl_context context, cl_command_queue queue,
cl_program program, cl_kernel kernel, cl_mem mem){
if(mem != 0){
clReleaseMemObject(mem);
}
if(queue != 0){
clReleaseCommandQueue(queue);
}
if(kernel != 0){
clReleaseKernel(kernel);
}
if(program != 0){
clReleaseProgram(program);
}
if(context != 0){
clReleaseContext(context);
}
}
int main(){
cl_int status;
cl_platform_id platform;
cl_device_id device;
cl_context context = NULL;
cl_command_queue queue = NULL;
cl_program program = NULL;
cl_kernel kernel = NULL;
status = clGetPlatformIDs(1, &platform, NULL);
status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
context = clCreateContext(NULL, 1, &device, NULL, NULL, &status);
queue = clCreateCommandQueue(context, device, 0, &status);
if(status != CL_SUCCESS){
printf("Failed to create context, status = %d.\n", status);
cleanUp(context, queue, NULL, NULL, NULL);
return 0;
}
char *source = readFile();
if(source == NULL) return 0;
size_t source_length = strlen(source);
program = clCreateProgramWithSource(context, 1, (const char **)&source, &source_length, &status);
if(program == NULL){
printf("Failed to read create program");
cleanUp(context, queue, program, NULL, NULL);
free(source);
return 0;
}
status = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if(status != CL_SUCCESS){
char buildlog[16384];
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, sizeof(buildlog), buildlog, NULL);
printf("Error in kernel:\n%s", buildlog);
cleanUp(context, queue, program, NULL, NULL);
free(source);
return 0;
}
free(source);
return 0;
}