如何替换C标准库函数? [英] How to replace C standard library function ?

查看:541
本文介绍了如何替换C标准库函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何替换C标准库函数与我们自己的实现,它的功能?

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

例如,我怎能取代的strcpy()用我自己的实施的strcpy()并让所有的调用链接到新的实现呢?

For example, how can I replace strcpy() with my own implementation of strcpy() and have all calls link to the new implementations instead?

推荐答案

至少与海湾合作委员会和glibc,标准C函数符号的的,因此您可以覆盖他们。例如,

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;
}

和构建它是这样的:

gcc -fno-builtin -o strcpy strcpy.c

和则:

$ ./strcpy 
Called my strcpy()
hello

请注意的重要性-fno-内置在这里。如果你不使用它,GCC将取代的strcpy()调用内建函数,其中GCC有一个数字。

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.

这篇关于如何替换C标准库函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆