title: How does this C program compile and run with two main functions?
body: <p>Today, while working with one custom library, I found a strange behavior.
  A static library code contained a debug <code>main()</code> function. It wasn't inside a <code>#define</code> flag. So it is present in library also. And it is used link to another program which contained the real <code>main()</code>.<br>
  When both of them are linked together, the linker didn't throw a multiple declaration error for <code>main()</code>. I was wondering how this could happen.</p>
  
  <p>To make it simple, I have created a sample program which simulated the same behavior:</p>
  
  <pre><code>$ cat prog.c
  #include &lt;stdio.h&gt;
  int main()
  {
          printf("Main in prog.c\n");
  }
  
  $ cat static.c
  #include &lt;stdio.h&gt;
  int main()
  {
          printf("Main in static.c\n");
  }
  
  $ gcc -c static.c
  $ ar rcs libstatic.a static.o
  $ gcc prog.c -L. -lstatic -o 2main
  $ gcc -L. -lstatic -o 1main
  
  $ ./2main
  Main in prog.c
  $ ./1main
  Main in static.c
  </code></pre>
  
  <p>How does the "2main" binary find which <code>main</code> to execute?</p>
  
  <p>But compiling both of them together gives a multiple declaration error:</p>
  
  <pre><code>$ gcc prog.c static.o
  static.o: In function `main':
  static.c:(.text+0x0): multiple definition of `main'
  /tmp/ccrFqgkh.o:prog.c:(.text+0x0): first defined here
  collect2: ld returned 1 exit status
  </code></pre>
  
  <p>Can anyone please explain this behavior?</p>