title: "undefined reference to" errors when linking static C library with C++ code
body: <p>I have a test file (just for the link test) where I overload the <code>new</code>/<code>delete</code> operators with my own <code>malloc</code>/<code>free</code> library called <code>libxmalloc.a</code>. But I keep getting "undefined reference to" error as following when linking the static library, even I change the order of <code>test.o</code> and <code>-lxmalloc</code>. But everything works well with other C programs linking this library. I'm so confused with this issue and appreciate any clue.</p>
  
  <p>Error Msg:</p>
  
  <pre><code>g++ -m64 -O3 -I/usr/include/ethos -I/usr/include/nacl/x86_64 -c -o test.o test.cpp
  g++ -m64 -O3 -L. -o demo test.o -lxmalloc
  test.o: In function `operator new(unsigned long)':
  test.cpp:(.text+0x1): undefined reference to `malloc(unsigned long)'
  test.o: In function `operator delete(void*)':
  test.cpp:(.text+0x11): undefined reference to `free(void*)'
  test.o: In function `operator new[](unsigned long)':
  test.cpp:(.text+0x21): undefined reference to `malloc(unsigned long)'
  test.o: In function `operator delete[](void*)':
  test.cpp:(.text+0x31): undefined reference to `free(void*)'
  test.o: In function `main':
  test.cpp:(.text.startup+0xc): undefined reference to `malloc(unsigned long)'
  test.cpp:(.text.startup+0x19): undefined reference to `malloc(unsigned long)'
  test.cpp:(.text.startup+0x24): undefined reference to `free(void*)'
  test.cpp:(.text.startup+0x31): undefined reference to `free(void*)'
  collect2: ld returned 1 exit status
  make: *** [demo] Error 1
  </code></pre>
  
  <p>My <code>test.cpp</code> file:</p>
  
  <pre><code>#include &lt;dual/xalloc.h&gt;
  #include &lt;dual/xmalloc.h&gt;
  void*
  operator new (size_t sz)
  {
      return malloc(sz);
  }
  void
  operator delete (void *ptr)
  {
      free(ptr);
  }
  void*
  operator new[] (size_t sz)
  {
      return malloc(sz);
  }
  void
  operator delete[] (void *ptr)
  {
      free(ptr);
  }
  int
  main(void)
  {
      int *iP = new int;
      int *aP = new int[3];
      delete iP;
      delete[] aP;
      return 0;
  }
  </code></pre>
  
  <p>My <code>Makefile</code>:</p>
  
  <pre><code>CFLAGS += -m64 -O3 -I/usr/include/ethos -I/usr/include/nacl/x86_64
  CXXFLAGS += -m64 -O3
  LIBDIR += -L.
  LIBS += -lxmalloc
  all: demo
  demo: test.o
      $(CXX) $(CXXFLAGS) $(LIBDIR) -o demo test.o $(LIBS)
  test.o: test.cpp
  $(CXX) $(CFLAGS) -c -o $@ $&lt;
  clean:
  - rm -f *.o demo
  </code></pre>