C++ &引用;未定义的引用;将静态C库链接到C++;代码

C++ &引用;未定义的引用;将静态C库链接到C++;代码,c++,c,static-libraries,C++,C,Static Libraries,我有一个测试文件(仅用于链接测试),其中我使用自己的malloc/免费库libxmalloc.a重载new/delete操作符。但是在链接静态库时,我不断得到如下“undefined reference to”错误,即使我更改了test.o和-lxmalloc的顺序。但是,与链接此库的其他C程序配合使用时,一切都很好。我对这个问题很困惑,希望你能给我一些线索 错误消息: g++ -m64 -O3 -I/usr/include/ethos -I/usr/include/nacl/x86_64 -c

我有一个测试文件(仅用于链接测试),其中我使用自己的
malloc
/
免费
libxmalloc.a
重载
new
/
delete
操作符。但是在链接静态库时,我不断得到如下“undefined reference to”错误,即使我更改了
test.o
-lxmalloc
的顺序。但是,与链接此库的其他C程序配合使用时,一切都很好。我对这个问题很困惑,希望你能给我一些线索

错误消息:

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;
}
但是,与链接此库的其他C程序配合使用时,一切都很好

<>你注意到C和C++编译在对象文件级上创建了不同的符号名吗?它被称为“”。
(C++)链接器会在错误消息中将未定义的引用显示为demangled符号,这可能会让您感到困惑。如果使用
nm-u
检查
test.o
文件,您会发现引用的符号名称与库中提供的符号名称不匹配

如果您想使用外部函数,使用纯C编译器编译的外部函数,那么您需要在<代码>外部的“C”{} /Cuth>块中包含它们的函数声明,这些语句禁止C++声明名称,用于内部声明或定义的所有内容,例如:

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

你试过使用
extern“C”{#include…}
?看起来像是一个很好的规范,不是已经有了吗?
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