title: Dynamic link with dlopen: symbol not found
body: <p>I want to load my own dynamic link library for C++, here is my test code:</p>
  
  <p>add.cpp</p>
  
  <pre><code>#include &lt;vector&gt;
  using namespace std;
  int add(int c)
  {
  
      vector&lt;int&gt; v;
  
      int i;
      int sum = 0;
      for (i = 0; i &lt; c; i++)
      {
          sum = sum + i;
      }
      return sum;
  }
  </code></pre>
  
  <p>I execute the command as below to build the <code>add.so</code>:</p>
  
  <pre><code>g++ -fPIC -shared add.cpp -o add.so
  </code></pre>
  
  <p>Then I try to link it to my C++ project dynamically with <code>dlopen</code>:</p>
  
  <p>main.cpp</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;dlfcn.h&gt;
  
  typedef int (*add_func_ptr)(int);
  
      int main(int argc, char **argv)
  {
      void *handle;
      double (*cosine)(double);
      char *error;
  
      handle = dlopen("./add.so", RTLD_LAZY);
      if (!handle)
      {
          fputs(dlerror(), stderr);
          exit(1);
      }
  
      add_func_ptr addfun;
      addfun = (add_func_ptr)dlsym(handle, "add");
      if ((error = dlerror()) != NULL)
      {
          fputs(error, stderr);
          exit(1);
      }
  
      printf("%d\n", (*addfun)(2));
      dlclose(handle);
  }
  </code></pre>
  
  <p>Lastly, I compile it:</p>
  
  <pre><code>g++ main.cpp -ldl -o main
  </code></pre>
  
  <p>However, when I execute <code>./main</code>, I always get the error: <code>symbol not found</code>.</p>
  
  <p>There is a similar <a href="https://stackoverflow.com/questions/3159395/why-symbols-of-a-shared-library-are-not-resolved-at-link-time">question</a>, but the answer could not solve my problem. I know the issue may be caused by the name mangling in C++ but I don't know how to solve it, I want to use <code>std::vector</code> in the dynamic link, so I need to use C++ instead of c to build .so file.</p>