title: MacOS -- how to link a dynamic library with a relative path using gcc/ld
body: <p>If you are trying to understand dynamic linking, <a href="https://stackoverflow.com/questions/194485/how-do-i-create-a-dynamic-library-dylib-with-xcode">this question</a> is likely to be of interest.</p>
  
  <p>One of the answers to that question provides a wonderful example of creating and using a dynamic library.  Based on it, I some simple files:</p>
  
  <p>main.c:</p>
  
  <pre><code>extern void someFunction (int x);
  
  int main (int argc, char** argv ) {
      someFunction(666);
  }
  </code></pre>
  
  <p>mylibrary.c:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  void someFunction (int x) {
      printf ("\nsomeFunction called with x=%d\n", x);
  }
  </code></pre>
  
  <p>makefile:</p>
  
  <pre><code>main: mylibrary.c main.c
      gcc -c mylibrary.c
      gcc -dynamiclib -current_version 1.0 mylibrary.o -o libmylibrary.dylib
      gcc -c main.c
      gcc -v main.o ./libmylibrary.dylib -o main
  
  clean:
      rm *.o
      rm main
      rm *.dylib
  </code></pre>
  
  <p>So far, everything works great.  If I make and then enter ./main at the command prompt, I see the expected output:</p>
  
  <pre><code>someFunction called with x=666
  </code></pre>
  
  <p>Now, I want to mix things up a little.  I've created a directory hidelib, which is a subdirectory of my main directory.  And I'm adding one line to my makefile:</p>
  
  <pre><code>main: mylibrary.c main.c
      gcc -c mylibrary.c
      gcc -dynamiclib -current_version 1.0 mylibrary.o -o libmylibrary.dylib
      gcc -c main.c
      mv libmylibrary.dylib hidelib     # this is the new line
  
  clean:
      rm *.o
      rm main
      rm hidelib/*.*
  </code></pre>
  
  <p>Now, I want to add another line to the makefile so it will find libmylibrary.dylib in the hidelib subdirectory.  I want to be able to run ./main in the same way.  How can I do that?</p>
  
  <p>EDIT:  Thanks for the response.  Having lots of options is wonderful, but a beginner just wants one concrete option that works.  Here is what I am trying for the last line, but clearly I don't understand something.  The makefile executes without errors, but at runtime it says "library not found."</p>
  
  <pre><code>    gcc main.o -rpath,'$$ORIGIN/hidelib' -lmylibrary -o main
  </code></pre>