title: Has anyone an example for wrapping a function in C++?
body: <p>I have searched online a lot but I couldn't find an example that works with g+, all examples work with GCC.</p>
  
  <p>The error I keep getting is:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>The code that creates this error is the following (this code works if I compile it with GCC and change the headers from cstdio to stdio.h):</p>
  
  <pre><code>#include &lt;cstdio&gt;
  #include &lt;cstdlib&gt;
  
  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;
  }
  </code></pre>
  
  <p>This is how I compile it:</p>
  
  <pre><code>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
  </code></pre>