title: Creating a shared library with main()
body: <p>In <a href="https://www.gnu.org/software/libc/" rel="nofollow noreferrer">glibc</a> (and also <a href="http://www.eglibc.org/home" rel="nofollow noreferrer">EGLIBC</a> I believe), the <code>libc.so</code> library has a <code>main()</code> method:</p>
  
  <pre><code>$ /lib/i386-linux-gnu/libc.so.6
  GNU C Library (Debian GLIBC 2.19-18+deb8u1) stable release version 2.19, by Roland McGrath et al.
  Copyright (C) 2014 Free Software Foundation, Inc.
  This is free software; see the source for copying conditions.
  There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
  PARTICULAR PURPOSE.
  Compiled by GNU CC version 4.8.4.
  Compiled on a Linux 3.16.7 system on 2015-08-30.
  Available extensions:
          crypt add-on version 2.1 by Michael Glad and others
          GNU Libidn by Simon Josefsson
          Native POSIX Threads Library by Ulrich Drepper et al
          BIND-8.2.3-T5B
  libc ABIs: UNIQUE IFUNC
  For bug reporting instructions, please see:
  &lt;http://www.debian.org/Bugs/&gt;.
  </code></pre>
  
  <p>Now I want to do the same with the following minimalistic example (i. e. I want my own SO to also have a <code>main()</code>):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main(int argc, char *argv[]) {
          printf("Hello, World!\n");
          return 0;
  }
  </code></pre>
  
  <p>Linking as a regular executable:</p>
  
  <pre><code>$ gcc -g -O0 -Wall -c test.c
  $ gcc -o test test.o
  $ ./test
  Hello, World!
  </code></pre>
  
  <p>Now linking as a shared object:</p>
  
  <pre><code>$ gcc -g -O0 -Wall -c test.c
  $ gcc -shared -o libtest.so test.o
  $ ./libtest.so
  Segmentation fault
  </code></pre>
  
  <ul>
  <li><code>nm</code> shows that <code>main</code> symbol is present (<code>000004f5 T main</code>)</li>
  <li>When debugging, <code>gdb</code> doesn't show any meaningful backtrace.</li>
  <li>Adding <code>-fpic</code> or <code>-fPIC</code> to the gcc command line doesn't help.</li>
  </ul>
  
  <p>What am I doing wrong?</p>