gpt4 book ai didi

c++ - 将静态 C 库与 C++ 代码链接时出现 "undefined reference to"错误

转载 作者:行者123 更新时间:2023-11-30 17:01:26 25 4
gpt4 key购买 nike

我有一个测试文件(仅用于链接测试),其中我重载了 new/delete与我自己的运营商malloc/free名为 libxmalloc.a 的库。但是在链接静态库时,我不断收到“ undefined reference ”错误,如下所示,即使我更改 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;
}

我的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++) 链接器会将 undefined reference 显示为错误消息中的分解符号,这可能会让您感到困惑。如果您使用 nm -u 检查 test.o 文件,您会发现引用的符号名称与库中提供的符号名称不匹配。

如果您想使用作为外部链接的函数,这些函数是使用普通 C 编译器编译的,则需要将它们的函数声明包含在 extern "C"{} block 中,该 block 会抑制 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

关于c++ - 将静态 C 库与 C++ 代码链接时出现 "undefined reference to"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37064544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com