title: Linking C compiled static library to C++ Program
body: <p>I tried to link a static library (compiled with gcc) to a c++ program and I got 'undefined reference'. I used gcc and g++ version 4.6.3 on a ubuntu 12.04 server machine. For example, here is the simple library file for factorial method:</p>
  
  <p><strong>mylib.h</strong></p>
  
  <pre><code>#ifndef __MYLIB_H_
  #define __MYLIB_H_
  
  int factorial(int n);
  
  #endif
  </code></pre>
  
  <p><strong>mylib.c</strong></p>
  
  <pre><code>#include "mylib.h"
  
  int factorial(int n)
  {
      return ((n&gt;=1)?(n*factorial(n-1)):1);
  }
  </code></pre>
  
  <p>I created object for this mylib.c using gcc:</p>
  
  <pre><code>gcc -o mylib.o -c mylib.c
  </code></pre>
  
  <p>Again the static library was created from the object file using AR utility:</p>
  
  <pre><code>ar -cvq libfact.a mylib.o
  </code></pre>
  
  <p>I tested this library with a C program (test.c) and C++ program (test.cpp)</p>
  
  <p>Both C and C++ program have the same body:</p>
  
  <pre><code>#include "mylib.h"
  int main()
  {
      int fact = factorial(5);
      return 0;
  }
  </code></pre>
  
  <p>Assuming static library libfact.a is available in /home/test directory, I compiled my C program without any issues:</p>
  
  <pre><code>gcc test.c -L/home/test -lfact
  </code></pre>
  
  <p>However while testing C++ program, it threw a link error:</p>
  
  <pre><code>g++ test.cpp -L/home/test -lfact
  
  test.cpp:(.text+0x2f): undefined reference to `factorial(int)'
  collect2: ld returned 1 exit status
  </code></pre>
  
  <p>I even tried adding extern command in test.cpp:</p>
  
  <pre><code>extern int factorial(int n) //added just before the main () function
  </code></pre>
  
  <p>Still the same error. </p>
  
  <ul>
  <li>Can someone tell me what I am wrong here?</li>
  <li>Is there anything I missed while creating the static library?</li>
  <li>Do I have to add anything in my <code>test.cpp</code> to make it work?</li>
  </ul>