How to replace C standard library function ?

前端 未结 3 2027
生来不讨喜
生来不讨喜 2020-12-15 11:18

How can we replace a C standard library function with our own implementation of that function ?

For example, how can I replace strcpy() with my own imp

相关标签:
3条回答
  • 2020-12-15 11:46

    I'm not sure how hard it will be to get the linker to do what you want, but here's a solution that doesn't involve changing any linker settings and uses preprocessor macros instead so that any code that tries to call strcpy actually calls a function called my_strcpy:

    mystuff.h:

    #define strcpy my_strcpy
    char * my_strcpy(char * dst, const char * src);
    

    my_strcpy.c:

    #include <mystuff.h>
    char * my_strcpy(char * dst, const char * src);
    {
        ...
    }
    

    my_code.c:

    #include <mystuff.h>
    
    int main()
    {
       /* Any call to strcpy will look like a normal call to strcpy
          but will actually call my_strcpy. */
    }
    
    0 讨论(0)
  • 2020-12-15 11:55

    You can try playing with LD_PRELOAD if you are on Linux.

    0 讨论(0)
  • 2020-12-15 11:58

    At least with GCC and glibc, the symbols for the standard C functions are weak and thus you can override them. For example,

    strcpy.c:

    #include <string.h>
    #include <stdio.h>
    
    char * strcpy(char *dst, const char *src)
    {
      char *d = dst;
      while (*src) {
        *d = *src;
        d++;
        src++;
      }
      printf("Called my strcpy()\n");
    
      return (dst);
    }
    
    int main(void)
    {
      char foo[10];
      strcpy(foo, "hello");
    
      puts(foo);
    
      return 0;
    }
    

    And build it like this:

    gcc -fno-builtin -o strcpy strcpy.c
    

    and then:

    $ ./strcpy 
    Called my strcpy()
    hello
    

    Note the importance of -fno-builtin here. If you don't use this, GCC will replace the strcpy() call to a builtin function, of which GCC has a number.

    I'm not sure if this works with other compilers/platforms.

    0 讨论(0)
提交回复
热议问题