"undefined reference to" errors when linking static C library with C++ code
Solution 1:
But everything works well with other C programs linking this library.
Did you notice that C and C++ compilation create different symbol names on object file level? It's called 'name mangling'.
The (C++) linker would show undefined references as demangled symbols in the error message, which might confuse you. If you inspect your test.o
file with nm -u
you'll see that the referenced symbol names don't match with those provided in your library.
If you want to use functions linked in as externals that were compiled using the plain C compiler, you'll need their function declarations enclosed in an extern "C" {}
block which suppresses C++ name mangling for everything declared or defined inside, e.g.:
extern "C"
{
#include <dual/xalloc.h>
#include <dual/xmalloc.h>
}
Even better, you might wrap your function declarations in your header files like this:
#if defined (__cplusplus)
extern "C" {
#endif
/*
* Put plain C function declarations here ...
*/
#if defined (__cplusplus)
}
#endif