Using clang to compile .cl kernel file

My environment:

Ubuntu clang version 12.0.0-3ubuntu1~20.04.3
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

My problem: when I do this:

$ clang -cl-std=CLC++ ./test.cl

in which ./test.cl file is:

template<class T>
T add( T x, T y )
{
    return x + y;
}
kernel void k(){}

an error raises that:

/usr/bin/ld: /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crt1.o: in function _start': (.text+0x24): undefined reference to main'

I wonder how I can solve this problem? I can't even compile the simplest .cl file which supports C++ features. Thanks guys!

1 answer

  • answered 2021-07-26 17:26 ProjectPhysX

    You don't compile .cl files with clang. You compile the .c/.cpp C/C++ source files. In the C/C++ code, you load the .cl file in as a string (kernel_code) and pass it to the OpenCL C/C++ bindings along with a device. The executable will then at runtime compile the OpenCL C code from the kernel_code string and pass the vendor-specific assembly onto the device (GPU).

    Here is the C++ code that does the CpenCL C compulation at runtime:

    //const cl::Device device = ...;
    //const string kernel_code = ...;
    
    cl::Context context = cl::Context(device);
    cl::CommandQueue queue = cl::CommandQueue(context, device); // queue to push commands for the device
    cl::Program::Sources source;
    source.push_back({ kernel_code.c_str(), kernel_code.length() });
    cl::Program program = cl::Program(context, source);
    int error = program.build("-cl-fast-relaxed-math"); // compile OpenCL C code
    if(error) cout << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << endl; // print build log if errors occur during OpenCL C compiling
    

    You then create cl::Buffer objects (allocate device memory), create cl::Kernel objects corresponding to the kernels in the OpenCL C code, link the buffers to the kernels in the correct order with kernel.setArg(...); and run the kernels in the queue with queue.enqueueNDRangeKernel(...); and queue.finish();.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum