title: dlsym returns NULL, even though the symbol exists
body: <p>I am using dlsym to look up symbols in my program, but it always returns NULL, which I am not expecting. According to the manpage, dlsym may return NULL if there was an error somehow, or if the symbol indeed is NULL. In my case, I am getting an error. I will show you the MCVE I have made this evening. </p>
  
  <p>Here is the contents of instr.c:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  void * testing(int i) {
      printf("You called testing(%d)\n", i);
      return 0;
  }
  </code></pre>
  
  <p>A very simple thing containing only an unremarkable example function.</p>
  
  <p>Here is the contents of test.c:</p>
  
  <pre><code>#include &lt;dlfcn.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  typedef void * (*dltest)(int);
  
  int main(int argc, char ** argv) {
  
      /* Declare and set a pointer to a function in the executable */
      void * handle = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL);
      dlerror();
      dltest fn = dlsym(handle, "testing");
  
      if(fn == NULL) {
          printf("%s\n", dlerror());
          dlclose(handle);
          return 1;
      }
      dlclose(handle);
      return 0;
  }
  </code></pre>
  
  <p>As I step through the code with the debugger, I see the dlopen is returning a handle. According to the manpage, <code>If filename is NULL, then the returned handle is for the main program.</code> So if I link a symbol called <code>testing</code> into the main program, dlsym should find it, right?</p>
  
  <p>Here is the way that I am compiling and linking the program:</p>
  
  <pre><code>all: test
  
  instr.o: instr.c
      gcc -ggdb -Wall -c instr.c
  
  test.o: test.c 
      gcc -ggdb -Wall -c test.c
  
  test: test.o instr.o
      gcc -ldl -o test test.o instr.o 
  
  clean:
      rm -f *.o test
  </code></pre>
  
  <p>And when I build this program, and then do <code>objdump -t test | grep testing</code>, I see that the symbol <code>testing</code> is indeed there:</p>
  
  <pre><code>08048632 g     F .text  00000020              testing
  </code></pre>
  
  <p>Yet the output of my program is the error:</p>
  
  <pre><code>./test: undefined symbol: testing
  </code></pre>
  
  <p>I am not sure what I am doing wrong. I would appreciate if someone could shed some light on this problem.</p>