c++ - 有人有用 C++ 包装函数的例子吗?

标签 c++ linux gcc g++

我在网上搜索了很多,但找不到适用于 g+ 的示例,所有示例均适用于 GCC。

我不断收到的错误是:

wrap_malloc.o: In function `__wrap_malloc(unsigned int)':
wrap_malloc.cc:(.text+0x20): undefined reference to `__real_malloc(unsigned int)'
wrap_malloc.o: In function `main':
wrap_malloc.cc:(.text+0x37): undefined reference to `__wrap_malloc'
collect2: ld returned 1 exit status

导致此错误的代码如下(如果我使用 GCC 编译它并将 header 从 cstdio 更改为 stdio.h,则此代码有效):

#include <cstdio>
#include <cstdlib>

void *__real_malloc(size_t);

void *__wrap_malloc(size_t c) {
  printf("My malloc called with %d\n", c);
  return __real_malloc(c);
}

int main(void) {
  void *ptr = malloc(12);
  free(ptr);
  return 0;
}

我是这样编译的:

wrap_malloc.o: wrap_malloc.cc
    g++ -c wrap_malloc.cc -o wrap_malloc.o

wrap_malloc: wrap_malloc.o
    g++ wrap_malloc.o -o wrap_malloc -Wl,--wrap,malloc

最佳答案

当您使用 C++ 编译器时,所有名称都会被破坏。当您运行 nm wrap_malloc.o 时,这意味着什么就很清楚了,它应该给您这样的东西:

00000000 b .bss
00000000 d .data
00000000 r .rdata
00000000 t .text
         U __Z13__real_mallocj
00000000 T __Z13__wrap_mallocj
         U _printf

这意味着您使用 (U) 一个名为 __Z13__real_mallocj 的符号,并且您在文本段 (T) 中定义了一个名为__Z13__wrap_mallocj。但是您可能需要一个名为 __real_malloc 的符号。要实现这一点,您必须告诉编译器 __real_malloc 是 C 风格的函数,如下所示:

extern "C" void *__real_malloc(size_t);

extern "C" void *__wrap_malloc(size_t c) {
  printf("My malloc called with %d\n", c);
  return __real_malloc(c);
}

现在 nm 的输出是:

00000000 b .bss
00000000 d .data
00000000 r .rdata
00000000 t .text
         U ___real_malloc
00000000 T ___wrap_malloc
         U _printf

可以看到名称_printf没有改变。这是因为在头文件中,许多函数已经声明为 extern "C"

注意:我在 Windows 上的 cygwin 环境中完成了以上所有操作。这就是为什么在外部符号中有一个额外的前导下划线。

关于c++ - 有人有用 C++ 包装函数的例子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3826108/

相关文章:

linux - 如何将 '<' 和 '>' 传递给 bash 脚本?

linux - Windows 文件命名问题

c - 带有内联汇编段错误的程序,除非以函数调用为前缀

c# - C# 程序员在 C++ 中读取 ProcessMemory,始终失败

c++ - 将 if/assign 转换为线程安全的 CAS 操作

linux - 在 Linux 中删除包含这两种模式的行

c++ - 如何提高 Visual C++ 编译时间?

c++ - 在 C++ 中检查用户输入的正确值

c++ - C++ 中的 CPU 定时器

c++ - 是否可以在 C++ 中对 C 结构进行子类化并在 C 代码中使用指向该结构的指针?