use*_*006 33 c c++ static-libraries
我有一个测试文件(仅用于链接测试),其中我使用我自己的/ 库调用来重载new/ delete运算符.但是在链接静态库时,我一直得到"未定义的引用"错误,即使我改变了和的顺序.但是一切都适用于连接这个库的其他C程序.我对这个问题很困惑,并且感谢任何线索.mallocfreelibxmalloc.atest.o-lxmalloc
错误消息:
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
πάν*_*ῥεῖ 63
但是一切都适用于连接这个库的其他C程序.
您是否注意到C和C++编译在目标文件级别创建了不同的符号名称?它被称为' 名称重整 '.
(C++)链接器会在错误消息中显示未定义的引用作为解码符号,这可能会使您感到困惑.如果您检查test.o文件,nm -u您将看到引用的符号名称与库中提供的符号名称不匹配.
如果你想使用以普通C编译器编译的外部链接的函数,你需要将它们的函数声明包含在一个extern "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