如何在Linux中重新定义malloc()以用于C new
我为我定义了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()和朋友?我希望这可以内置,但它们是未定义的. 解决方法
我假设您在main.cpp文件中定义了malloc和free,您尝试编译并且mem_alloc和mem_free位于libmemnmf-0.a中
可能发生的是,main.cpp中的一些引用需要来自glibc的对象.具体来说,有些东西是动态加载库(dlopen).这段代码包含在glibc中(回答问题2). 你应该做的是将malloc和free例程放在一个单独的.o文件中,并在link-command中的某处添加该文件,最好是在最后(假设你没有在该行上以特殊方式指定标准库). .o文件将满足所有符号请求,并且glibc库将在dlopen或其他对象需要时解析这些匹配. 如果要覆盖new和delete的行为,还可以查看重载operator new和operator delete for classes,以提供特定于类的分配方法或内存池. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |