链接静态C库与C代码时的“未定义引用”错误

我有一个测试文件(仅用于链接测试),我用自己的malloc / free库(libxmalloc.a)重新载入新的/删除的操作符。但是当链接静态库时,我仍然会得到“underdefined reference to”错误,即使我更改了test.o和-lxmalloc的顺序。但是一切与其他连接这个库的C程序一起工作。我对这个问题感到困惑,感谢任何线索。

错误MSg:

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

我的test.cpp文件:

#include <dual/xalloc.h>
#include <dual/xmalloc.h>
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;
}

我的Makefile:

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 $@ $<
clean:
- rm -f *.o demo

But everything works well with other C programs linking this library.

您是否注意到C和C编译在对象文件级别创建不同的符号名称?这叫’name mangling‘。
(C)链接器将在错误消息中将未定义的引用显示为已解除的符号,这可能会让您感到困惑。如果您使用nm -u检查test.o文件,您将看到引用的符号名称与库中提供的符号名称不匹配。

如果要使用使用普通C编译器编译的外部链接的函数,则需要将其函数声明包含在外部“C”{}块中,该块禁止对内部声明或定义的所有内容进行C名称修改,例如:

extern "C" 
{
    #include <dual/xalloc.h>
    #include <dual/xmalloc.h>
}

更好的是,您可以将这些函数声明包含在头文件中:

#if defined (__cplusplus)
extern "C" {
#endif

/*
 * Put plain C function declarations here ...
 */ 

#if defined (__cplusplus)
}
#endif
翻译自:https://stackoverflow.com/questions/18877437/undefined-reference-to-errors-when-linking-static-c-library-with-c-code

转载注明原文:链接静态C库与C代码时的“未定义引用”错误