Search code examples
c++g++cygwinstatic-linkingundefined-reference

Undefined Reference Error When Linking to Static Library


I am trying to compile a project that depends on the Xerces XML Parser. The project compiles for Windows without any difficulty, but I'm having some trouble compiling it with g++ in Cygwin.

In order to use Xerces, I am trying to compile my code against the static library libxerces-c.a. But when I do so, I get errors that look like this:

/tmp/cc2QGvMh.o:test.cpp:(.text+0x3a): undefined reference to `xercesc_2_8::DOMImplementationRegistry::getDOMImplementation(unsigned short const*)'

I've inspected the static library using ar, and confirmed that it contains the DOMImplementationRegistry.o file that defines the function that I am calling.

ar -t libxerces-c.a
...
DOMImplementationImpl.o
DOMImplementationRegistry.o
DOMLocatorImpl.o
...

I've also extracted the object files from the library, and used 'nm' to make sure that the function I am calling actually exists:

ar -x libxerces-c.a
nm --demangle DOMImplementationRegistry.o
...
00000080 T xercesc_2_8::getDOMImplSrcVectorMutex()
00000300 T xercesc_2_8::DOMImplementationRegistry::getDOMImplementation(unsigned short const*)
000002a0 T xercesc_2_8::DOMImplementationRegistry::addSource(xercesc_2_8::DOMImplementationSource*)
...

Since I can compile everything for Windows but not with g++, I thought that the error could be in the linker order (similar to the problem described in this question). However, even after changing the linker order, I am still getting the same compiler error. I have tried both

g++ -o test.exe test.cpp -Llib -lxerces-c

and

g++ -o test.exe test.cpp lib/libxerces-c.a

Any ideas?


Solution

  • You didn't say the source of the archive. If it isn't compiled with cygwin, it could be a name mangling problem. Compiling the library from source might well fix this.

    It could also be that the archive is built incorrectly so that it has internal resolution problems. Try giving the library name twice.

    g++ -o test.exe test.cpp lib/libxerces-c.a lib/libxerces-c.a
    

    If this works, the archive is broken and you should look for or build a new one.