c++ - 如何在 Linux 中重新定义 malloc() 以便在 C++ 中使用 new

标签 c++ malloc linker-errors redefine

我有一个为我定义的 mem_malloc() 和 mem_free(),我想用它们来替换 malloc() 和 free(),从而替换 C++ 的 new 和 delete。

我定义它们如下:

extern "C" {

extern void *mem_malloc(size_t);
extern void mem_free(void *);

void *
malloc(size_t size) {
  return mem_malloc(size);
}

void
free(void *memory) {
  mem_free(memory);
}
}

但是,我收到两个链接错误:

[user@machine test]$ g++ -m32 -pthread main.cpp -static  libmemnmf-O.a
/usr/lib/../lib/libc.a(malloc.o): In function `free':
(.text+0x153c): multiple definition of `free'
/tmp/ccD2Mgln.o:main.cpp:(.text+0x842): first defined here
/usr/lib/../lib/libc.a(malloc.o): In function `malloc':
(.text+0x3084): multiple definition of `malloc'
/tmp/ccD2Mgln.o:main.cpp:(.text+0x856): first defined here
libmemnmf-O.a(mem_debug.o): In function `mem_init_debug_routines':
mem_debug.c:(.text+0x83c): undefined reference to `dlopen'
mem_debug.c:(.text+0x89d): undefined reference to `dlsym'
mem_debug.c:(.text+0xa03): undefined reference to `dlclose'
mem_debug.c:(.text+0xa24): undefined reference to `dlclose'
mem_debug.c:(.text+0xa2e): undefined reference to `dlerror'
collect2: ld returned 1 exit status

1) 如何消除多重定义的 malloc() 和 free() 错误,并只采用我的定义而不是内置的?

2) 哪个库提供了 dlopen() 和 friend ?我希望这是内置的,但它们是未定义的。

最佳答案

我假设您在尝试编译的 main.cpp 文件中定义了 malloc 和 free,并且 mem_alloc 和 mem_free 位于 libmemnmf-0.a 中

可能发生的情况是,main.cpp 中的某些引用需要来自 glibc 的对象。具体来说,有些东西正在动态加载库(dlopen)。此代码包含在 glibc 中(回答问题 2)。 当链接器包含来自 glibc 的对象并发现这些对象需要 malloc/free 符号时,它将尝试直接包含来自 glibc 库的 malloc/free。 由于您的 -static 链接器标志,整个 libmemnmf-0.a 库静态包含在您的可执行文件中。这显然会在您的可执行文件中包含另一个 malloc 和自由对象。

你应该做的是将 malloc 和 free 例程放在一个单独的 .o 文件中,并将该文件添加到你的链接命令中的某个位置,最好是在末尾(假设你没有以特殊方式指定标准库线)。 .o 文件将满足所有符号请求,并且 glibc 库将在 dlopen 或其他对象需要它们时发现这些匹配已解决。 不同之处在于 libmnef-0.a 文件是一个库,链接器处理库的方式与处理简单对象的方式不同(这与通过库以解析该库中对象请求的符号的次数有关)。 或者,您可以删除 -static 标志,我希望它也能解决问题,但您可能有充分的理由在开始时包含该标志。

如果要覆盖 new 和 delete 的行为,还可以考虑为类重载 operator new 和 operator delete 以提供特定于类的分配方法或内存池。

关于c++ - 如何在 Linux 中重新定义 malloc() 以便在 C++ 中使用 new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4364647/

相关文章:

c - 如果请求的内存空间很大,Malloc 是否只使用堆?

c - 在 malloc 的内存上使用 sizeof()

c++ - 如何将对象读/写到文件

c - c中malloc的使用

c++ - 将 CUDA 添加到 ROS 包

c++ - CUDA C++ 链接错误 undefined reference threadIdx.x

c++ - 此代码是否损坏或 g++ 中是否存在错误?

c++ - 优化 C++11 随机生成器的使用

c++ - 用 C++ 将未压缩的 TGA 写入文件

c++ - gcc - 如何创建目标文件的映射文件