title: Dynamic Shared Library compilation with g++
body: <p>I'm trying to compile the following simple DL library example code from <a href="http://tldp.org/HOWTO/Program-Library-HOWTO/dl-libraries.html" rel="noreferrer">Program-Library-HOWTO</a> with g++.  This is just an example so I can learn how to use and write shared libraries.  The real code for the library I'm developing will be written in C++.</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;dlfcn.h&gt;
  
  int main(int argc, char **argv) {
      void *handle;
      double (*cosine)(double);
      char *error;
  
      handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
      if (!handle) {
          fputs (dlerror(), stderr);
          exit(1);
      }
  
      cosine = dlsym(handle, "cos");
      if ((error = dlerror()) != NULL)  {
          fputs(error, stderr);
          exit(1);
      }
  
      printf ("%f\n", (*cosine)(2.0));
      dlclose(handle);
  }
  </code></pre>
  
  <p>If I compile the program with gcc it works fine.</p>
  
  <pre><code>gcc -o foo foo.c -ldl
  </code></pre>
  
  <p>When I change the filename and compiler to the following</p>
  
  <pre><code>g++ -o foo foo.cpp -ldl
  </code></pre>
  
  <p>I get the following error:</p>
  
  <blockquote>
    <p>foo.cpp:16: error: invalid conversion from 'void*' to 'double (*)(double)'</p>
  </blockquote>
  
  <p>I understand (I <em>think</em> I understand, correct me if this is wrong) that I can't do an implicit cast from a void pointer in C++, but C lets me, and this is why the above code will compile using gcc but not using g++.  So I tried an explicit cast by changing line 16 above to:</p>
  
  <pre><code>cosine = (double *)dlsym(handle, "cos");
  </code></pre>
  
  <p>With this in place, I get the following error:</p>
  
  <blockquote>
    <p>foo.cpp:16: error: cannot convert 'double*' to 'double (*)(double)' in assignment</p>
  </blockquote>
  
  <p>These problems probably have more to do with my own general ignorance of proper C++ coding standards than anything else.  Can anyone point me to a good tutorial on developing dynamic libraries for Linux that uses C++ example code?</p>