Dynamic Shared Library compilation with g++

dlsym returns a pointer to the symbol. (As void* to be generic.) In your case you should cast it to a function-pointer.

 double (*mycosine)(double); // declare function pointer
 mycosine = (double (*)(double)) dlsym(handle, "cos"); // cast to function pointer and assign

 double one = mycosine(0.0); // cos(0)

So this one of these rare cases where the compiler error is a good clue. ;)


C allows implicit casts from void * to any pointer type (including function pointers); C++ requires explicit casting. As leiflundgren says, you need to cast the return value of dlsym() to the function pointer type you need.

Many people find C's function pointer syntax awkward. One common pattern is to typedef the function pointer:

typedef double (*cosine_func_ptr)(double);

You can define your function pointer variable cosine as a member of your type:

cosine_func_ptr cosine;

And cast using the type instead of the awkward function pointer syntax:

cosine = (cosine_func_ptr)dlsym(handle, "cos");