wiki:OpenCL_Template

Version 2 (modified by nakasato, 14 years ago) (diff)

--

Template Makefile

CFLAGS=-Wall -O

PATH_TO_AMD:=/opt/opencl
PATH_TO_AMD_LIB=$(PATH_TO_AMD)/lib/x86_64
PATH_TO_AMD_INC=$(PATH_TO_AMD)/include

EXE_NAME=test.exe

$(EXE_NAME): temp.cpp
        g++ $(CFLAGS) -I$(PATH_TO_AMD_INC) -L$(PATH_TO_AMD_LIB) -o $@ $< -lOpenCL


clean:
        rm -f $(EXE_NAME)

Template source program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/cl.h>
#endif

#define MAX_SOURCE_SIZE (0x100000)

int main()
{
    cl_platform_id platform_id = NULL;
    cl_device_id device_id = NULL;
    cl_context context = NULL;
    cl_program program = NULL;
    cl_uint ret_num_devices;
    cl_uint ret_num_platforms;
    cl_int ret;

    FILE *fp;
    const char fileName[] = "temp.cl";
    size_t source_size;
    char *source_str;
   
    ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms);
    ret = clGetDeviceIDs( platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices);
    
    context = clCreateContext( NULL, 1, &device_id, NULL, NULL, &ret);
    
    fp = fopen(fileName, "r");
    if (!fp) {
        fprintf(stderr, "Failed to load kernel.\n");
        exit(1);
    }
    source_str = (char *)malloc(MAX_SOURCE_SIZE);
    source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp );
    fclose( fp );
 
    program = clCreateProgramWithSource(context, 1, (const char **)&source_str, (const size_t *)&source_size, &ret);
    ret     = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);
    if(ret != CL_SUCCESS) {
      if(ret == CL_BUILD_PROGRAM_FAILURE) {
        cl_int logStatus;
        char * buildLog = NULL;
        size_t buildLogSize = 0;
 
        fprintf(stderr, "Error: %s\n", fileName);
        logStatus = clGetProgramBuildInfo (program,
                                           device_id,
                                           CL_PROGRAM_BUILD_LOG, 
                                           buildLogSize, 
                                           buildLog, 
                                           &buildLogSize);

        buildLog = (char*)malloc(buildLogSize);
        memset(buildLog, 0, buildLogSize);

        logStatus = clGetProgramBuildInfo (program, 
                                           device_id, 
                                           CL_PROGRAM_BUILD_LOG, 
                                           buildLogSize, 
                                           buildLog, 
                                           NULL);
        fprintf(stderr, "%s\n", buildLog);
        free(buildLog);
      }
      exit(-1);
    }

    free(source_str);

    clReleaseProgram(program);
    clReleaseContext(context);
    
    return 0;
}