title: How to set the runtime path (-rpath) of an executable with gcc under Mac OSX?
body: <p>I want to set under Mac OSX the runtime path of an executable (for the linker) at compile time, such that shared libraries at non-standard locations are found by the dynamic linker at program start.</p>
  
  <p>Under Linux this is possible with <code>-Xlinker -rpath -Xlinker /path/to</code> (or using <code>-Wl,-rpath,/path/to</code>) and under Solaris you can add <code>-R/path/to</code> to the compiler command line.</p>
  
  <p>I found <a href="http://blogs.oracle.com/dipol/entry/dynamic_libraries_rpath_and_mac" rel="noreferrer">some information</a> that Mac OS X gcc has -rpath support since 10.5, i.e. since ~ 2008.</p>
  
  <p>I tried to get it working with a minimal example - without success:</p>
  
  <pre><code>$ cat blah.c 
  int blah(int b)
  {
    return b+1;
  }
  </code></pre>
  
  <p>And:</p>
  
  <pre><code>$ cat main.c 
  
  #include &lt;stdio.h&gt;
  
  int blah(int);
  
  int main ()
  {
    printf("%d\n", blah(22));
    return 0;
  }
  </code></pre>
  
  <p>Compiled it like this:</p>
  
  <pre><code>$ gcc -c  blah.c
  $ gcc -dynamiclib blah.o -o libblah.dylib
  $ gcc main.c -lblah -L`pwd`  -Xlinker -rpath -Xlinker `pwd`/t
  </code></pre>
  
  <p>Now the test:</p>
  
  <pre><code>$ mkdir t
  $ mv libblah.dylib t
  $ ./a.out
  dyld: Library not loaded: libblah.dylib
    Referenced from: /Users/max/test/./a.out
    Reason: image not found
  Trace/BPT trap
  </code></pre>
  
  <p>Thus the question: How to I set the runtime path for the linker under Mac OSX?</p>
  
  <p>Btw, setting <code>DYLD_LIBRARY_PATH</code> works - but I don't want to use this hack.</p>
  
  <p><strong>Edit:</strong> Regarding <code>otool -L</code>:</p>
  
  <pre><code>$ otool -L a.out 
  a.out:
          libblah.dylib (compatibility version 0.0.0, current version 0.0.0)
          /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)
  </code></pre>
  
  <p>It seems that <code>otool -L</code> only prints the library names (and probable the locations at link time) the executable was linked against and no runtime path information.</p>