简体   繁体   English

如何替换C标准库函数?

[英]How to replace C standard library function ?

How can we replace a C standard library function with our own implementation of that function ? 我们如何用我们自己的函数实现替换C标准库函数?

For example, how can I replace strcpy() with my own implementation of strcpy() and have all calls link to the new implementations instead? 例如,如何将strcpy()替换为我自己的strcpy()实现,并将所有调用链接到新实现?

At least with GCC and glibc, the symbols for the standard C functions are weak and thus you can override them. 至少对于GCC和glibc,标准C函数的符号很弱 ,因此您可以覆盖它们。 For example, 例如,

strcpy.c: 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. 注意-fno-builtin在这里的重要性。 If you don't use this, GCC will replace the strcpy() call to a builtin function, of which GCC has a number. 如果你不使用它,GCC会将strcpy()调用替换为内置函数,其中GCC有一个数字。

I'm not sure if this works with other compilers/platforms. 我不确定这是否适用于其他编译器/平台。

如果你在Linux上,你可以尝试使用LD_PRELOAD

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: 我不确定让链接器做你想做的事情有多难,但是这里的解决方案不涉及更改任何链接器设置而是使用预处理器宏,以便任何试图调用strcpy的代码实际上都调用了函数my_strcpy:

mystuff.h: mystuff.h:

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

my_strcpy.c: my_strcpy.c:

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

my_code.c: 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. */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM