title: Link with relative paths in gcc
body: <p>I will use a simplified example to explain my case.</p>
  
  <p>I have <strong>two</strong> libme.so files which have different implementations and I already verified that they can work in a single design at the same time. One is located at ./root/v1/ and the other one is located at ./root/v2/</p>
  
  <p>My "main" .so file is linked with those 2 libme.so files and is located at ./root/libtest.so</p>
  
  <p>Now I have the requirement to make the things relocatable. That is, if I copy the entire "root" directory to another location or even another machine (assuming binary compatible), things should still work fine. </p>
  
  <p>My question is, to make this work, what gcc command line should I use to build libtest.so?</p>
  
  <p>I've tried the following two:</p>
  
  <p>(1) (assuming I'm in "root" directory)</p>
  
  <pre><code>&gt;gcc -shared -o libtest.so ./v1/libme.so ./v2/libme.so
  </code></pre>
  
  <p>This will make libtest.so has those 2 link dependencies both with absolute paths. This can be verified via ldd:</p>
  
  <pre><code>&gt;ldd libtest.so
  /home/design/root/v1/libme.so
  /home/design/root/v2/libme.so
  </code></pre>
  
  <p>Obviously the paths are fixed. So once I relocate the "root" directory, it cannot find libme.so at runtime. Note setting LD_LIBRARY_PATH doesn't work in this case since the path from ldd is absolute path. The runtimer loader will not search LD_LIBRARY_PATH to find libme.so.</p>
  
  <p>(2) </p>
  
  <pre><code>&gt;gcc -shared -o libtest.so -lme -L./v1 -L./v2
  </code></pre>
  
  <p>This will work only if we have a single version of libme.so. In this case, the version in ./v2 will not get linked in. The same issue exists for -rpath.</p>
  
  <p>Given that, what other options do I have?</p>
  
  <p>Note there are some restrictions:
  (1) cannot rename libme.so to other names such as libme_v1.so
  (2) libtest.so has to link in both versions of libme.so</p>