How to replace C standard library function ?

前端 未结 3 2052
生来不讨喜
生来不讨喜 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: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 
    #include 
    
    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.

提交回复
热议问题