title: About the -ldl flag while compiling and linking C++ files
body: <p>With reference to the following code</p>
  
  <p><strong>test_linker.cpp</strong></p>
  
  <pre><code>int main() {
  
      srand(time(0));
      for (int i = 0; i &lt; 10; ++i) {
          cout &lt;&lt; rand() % 10 &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p><strong>urandom.cpp</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  using std::cout;
  using std::endl;
  #include &lt;dlfcn.h&gt;
  
  int rand() throw() {
  
      // get the original rand() function
      static auto original_rand = (decltype(&amp;rand)) dlsym(RTLD_NEXT,"rand");
  
      cout &lt;&lt; "Call made to rand()" &lt;&lt; endl;
      return original_rand();
  }
  </code></pre>
  
  <p>When I try to compile the code with the following command</p>
  
  <pre><code>g++ -std=c++11 -Wall -Werror -Wextra -Wvla -pedantic -O3 urandom.cpp -c
  g++ -std=c++11 -Wall -O3 test_linker.cpp urandom.o -ldl
  </code></pre>
  
  <p>everything works fine, but when I move the <code>-ldl</code> flag to being before the files, the linker throws an error saying </p>
  
  <pre><code>urandom.cpp:(.text+0xaf): undefined reference to `dlsym'
  </code></pre>
  
  <p><strong>Question 1</strong> Could someone explain why this would happen?  I generally do not care about the order of flags in a compilation command. </p>
  
  <p><strong>Question 2</strong> Also is it wrong to keep the function pointer to the original <code>rand()</code> function a static variable? I do not know how exactly dynamic linking works and I am afraid that maybe the function address is moved around in memory at runtime.  The manual pages said that the <code>dlsym()</code> function with the <code>RTLD_NEXT</code> handle is an expensive computation so I just wanted to lazily evaluate this once. </p>
  
  <p>Note : I am compiling this on a Linux distribution and the Linux dynamic linker is involved so I will go ahead and tag this with Linux also. </p>