title: install_name_tool to update a executable to search for dylib in Mac OS X
body: <p>I have a dynamic libray libtest.dylib that is installed in <code>/PATH/lib</code>, and an execution binary, myapp, that uses the dylib installed in <code>/PATH/bin</code>. </p>
  
  <p>I can run <code>myapp</code> to find the dylib as follows (<a href="https://stackoverflow.com/questions/3146274/is-it-ok-to-use-dyld-library-path-on-mac-os-x-and-whats-the-dynamic-library-s">Is it OK to use DYLD_LIBRARY_PATH on Mac OS X? And, what&#39;s the dynamic library search algorithm with it?</a>):</p>
  
  <pre><code>DYLD_LIBRARY_PATH="/PATH/lib" myapp 
  </code></pre>
  
  <p>I think I can use <code>install_name_tool</code> to update the library and executable so that the library can be found with rpath. I used the hints in this post - <a href="https://stackoverflow.com/questions/17202313/how-can-i-specify-the-rpath-in-a-dylib">How can I specify the rpath in a dylib?</a>. </p>
  
  <p>In lib, I executed this command to add rpath.</p>
  
  <pre><code>install_name_tool -id "@rpath/libtest.dylib" libtest.dylib
  install_name_tool -add_rpath "@executable_path/../lib/" libtest.dylib
  </code></pre>
  
  <p>In bin, I executed <code>install_name_tool -add_rpath "@executable_path/../lib/" myapp</code>.</p>
  
  <p>However, when I executed <code>myapp</code> in <code>bin</code> directory, I have the error messages.</p>
  
  <pre><code>dyld: Library not loaded: libtest.dylib
    Referenced from: /PATH/bin/./myapp
    Reason: image not found
  Trace/BPT trap: 5
  </code></pre>
  
  <p><code>otool -l myapp</code> shows the rpath is correctly updated in myapp.</p>
  
  <pre><code>Load command 16
            cmd LC_RPATH
        cmdsize 40
           path @executable_path/../lib/ (offset 12)
  </code></pre>
  
  <p>The same is true with libtest.dylib</p>
  
  <pre><code>Load command 13
            cmd LC_RPATH
        cmdsize 40
           path @executable_path/../lib/ (offset 12)
  </code></pre>
  
  <p>What might be wrong? </p>
  
  <h2>ADDED</h2>
  
  <p>Of course, I can use <code>cc -install_name</code> when compile and link time, but I wanted to know how to do the same thing my modifying the generatd dylib and execution binary. </p>
  
  <p>From the lib:</p>
  
  <pre><code>cc -install_name "@loader_path/../lib/libtest.dylib" -dynamiclib -o libtest.dylib test.c
  </code></pre>
  
  <p>Or, the install_name can use @rpath:</p>
  
  <pre><code>cc -install_name "@rpath/libtest.dylib" -dynamiclib -o libtest.dylib test.c
  </code></pre>
  
  <p>From the bin:</p>
  
  <pre><code>cc -I../lib -c main.c
  cc -o main main.o ../lib/libtest.dylib -Wl,-rpath -Wl,@loader_path/../lib
  </code></pre>
  
  <p>Or just one line:</p>
  
  <pre><code>cc -I../lib -L../lib -o main main.c -ltest -Wl,-rpath -Wl,@loader_path/../lib
  </code></pre>