43

I have a test file (just for the link test) where I overload the new/delete operators with my own malloc/free library called libxmalloc.a. But I keep getting "undefined reference to" error as following when linking the static library, even I change the order of test.o and -lxmalloc. But everything works well with other C programs linking this library. I'm so confused with this issue and appreciate any clue.

Error 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

My test.cpp file:

#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;
}

My 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
4

1 回答 1

79

但是一切都适用于链接这个库的其他 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
于 2013-09-18T17:54:18.867 回答