Search code examples
c++mingwopencllinker-errorsundefined-reference

Linker can't find clGetPlatformIDs()?


I'm trying to compile a simple OpenCL test program using the AMD OCL SDK:

#include <stdio.h>
#include <CL/cl.h>

int main() {
    cl_platform_id platform;
    cl_device_id device;
    cl_uint num_platforms, num_devices;
    cl_int err;

    // Get the number of OpenCL platforms
    err = clGetPlatformIDs(1, &platform, &num_platforms);
    if (err != CL_SUCCESS) {
        fprintf(stderr, "Error getting platform IDs: %d\n", err);
        return 1;
    }

    printf("Number of OpenCL platforms: %u\n", num_platforms);

    // Get the number of devices for the chosen platform
    err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
    if (err != CL_SUCCESS) {
        fprintf(stderr, "Error getting device IDs: %d\n", err);
        return 1;
    }

    printf("Number of OpenCL devices: %u\n", num_devices);

    printf("OpenCL is working!\n");

    return 0;
}

However, whenever I try to compile it:

g++ main.cpp -o main -I./opencl/common/inc -L./opencl/common/lib/x64 -LOpenCL

...I get an error:

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\bradl\AppData\Local\Temp\cc04baXU.o:main.cpp:(.text+0x21): undefined reference to `clGetPlatformIDs'

I've tried changing the location of the OCL SDK to be within the project folder with no luck.


Solution

  • The reason for your issue is that you are not actually linking any library, instead you are adding two library paths.

    The reason is that you have only used -L (upper case), which adds the directory to the library search path. So -LOpenCL is also being treated as just another directory.

    The case is important, to add the library you should use -l (lower case)

    So your g++ line should look like this:

    g++ main.cpp -o main -I./opencl/common/inc -L./opencl/common/lib/x64 -lOpenCL