library is linked but reference is undefined

user615457 picture user615457 · Oct 16, 2011 · Viewed 50.1k times · Source

I'm trying to compile an openCL program on Ubuntu with an NVIDIA card that worked once before,

#include <CL/cl.h>
#include <iostream>
#include <vector>

using namespace std;

int main() {
  cl_platform_id platform;
  cl_device_id device;
  cl_context context;
  cl_command_queue command_queue;
  cl_int error;

  if(clGetPlatformIDs(1, &platform, NULL) != CL_SUCCESS) {
    cout << "platform error" << endl;
  }

  if(clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL) != CL_SUCCESS) {
    cout << "device error" << endl;
  }

  context = clCreateContext(NULL, 1, &device, NULL, NULL, &error);
  if(error != CL_SUCCESS) {
    cout << "context error" << endl;
  }

  command_queue = clCreateCommandQueue(context, device, 0, &error);
  if(error != CL_SUCCESS) {
    cout << "command queue error" << endl;
  }

  return 0;
}

I compile it like so,

g++ -I/usr/local/cuda/include -L/usr/lib/nvidia-current -lOpenCL opencl.cpp

and I get this result

/tmp/ccAdS9ig.o: In function `main':
opencl.cpp:(.text+0x1a): undefined reference to `clGetPlatformIDs'
opencl.cpp:(.text+0x3d): undefined reference to `clGetDeviceIDs'
opencl.cpp:(.text+0x65): undefined reference to `clCreateContext'
opencl.cpp:(.text+0x85): undefined reference to `clCreateCommandQueue'
collect2: ld returned 1 exit status

but nm -D /usr/lib/nvidia-current/libOpenCL.so tells me that libOpenCL.so at least contains clGetPlatformIDs

0000000000002400 T clGetKernelWorkGroupInfo
0000000000002140 T clGetMemObjectInfo
0000000000002e80 T clGetPlatformIDs
0000000000002de0 T clGetPlatformInfo
0000000000002310 T clGetProgramBuildInfo
00000000000022f0 T clGetProgramInfo
00000000000021f0 T clGetSamplerInfo

Am I missing something.

Answer

user995502 picture user995502 · Oct 28, 2011

when you are linking, the order of your libraries and source files makes a difference. for example for your case,

g++ -I/usr/local/cuda/include -L/usr/lib/nvidia-current -lOpenCL opencl.cpp

functions defined in the OpenCL library might not be loaded, since there nothing before them asking for a look-up. however if you use,

g++ opencl.cpp -I/usr/local/cuda/include -L/usr/lib/nvidia-current -lOpenCL  

then any requests for functions will be found in the OpenCL library and they will be loaded.