Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename/alias a function in C?

Tags:

c

function

alias

Say I have a library I am making and I want to call a function rename or puts, how can I keep the original rename and puts from stdlib or stdio or whatever, and yet have my own function be puts?

#include <stdio.h>

alias puts original_puts;

void
puts(char *c) {
  original_puts(c);
}

How can I accomplish something to this effect?

like image 610
Lance Avatar asked Jan 24 '26 01:01

Lance


2 Answers

You can't alias library functions, but you can alias your own using preprocessor directives.

For example:

mylib.h:

#include <stdio.h>

void my_puts(char *c);

#define puts(arg) my_puts(arg)

mylib.c:

void my_puts(char *c)
{
    (puts)(c);
}

Now, anytime someone calls puts, it substitutes a call to my_puts instead. Also, when you want to call the "real" function in your wrapper, you can put the function name in quotes. Because the macro that does the substitution is a function-like macro, the parenthesis prevent the substitution from happening.

like image 123
dbush Avatar answered Jan 25 '26 19:01

dbush


If compiling with gcc or clang, you can wrap the symbol with -Wl,--wrap:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int __real_puts(const char *c);
int __wrap_puts(const char *c) {
        __real_puts("Hello");
        __real_puts(c);
        return 0;
}

int main(int argc, char const *argv[]) {
        puts("world");
}   

$ gcc src.c -Wl,--wrap=puts && ./a.out
Hello
world
like image 27
KamilCuk Avatar answered Jan 25 '26 17:01

KamilCuk