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 implementation of strcpy()
and have all calls link to the new implementations instead?
But in pure C, with no extensions, and the standard library functions removed, you basically can't do anything other than read the command line arguments, do some work, and return a status code from main .
The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. Starting from the original ANSI C standard, it was developed at the same time as the C library POSIX specification, which is a superset of it.
If you need to use functions from standard library, you have to re-implement that functionality because of a simple reason - there is no standard C library. C library is basically implemented on the top of the Linux kernel (or other operating system's kernel).
C Standard library functions or simply C Library functions are inbuilt functions in C programming. The prototype and data definitions of these functions are present in their respective header files. To use these functions we need to include the header file in our program.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With