wangbo15
wangbo15

Reputation: 221

Does gcc wrap option takes effects on function printf ?

I wrote a wrap function to replace the printf of stdio.h. I found that the wrap option worked on functions in stdlib.h, like malloc or exit. But it did not work on printf or fprintf.

Does the option wrap takes effects on functions in stdio.h ? And how can I wrap an arbitrary function ? I cannot get useful guide from the ld document.

Here is the code :

//gcc wrap.c -g -Wl,--wrap,fprintf
int __real_fprintf(FILE *stream, const char *format, ...);

int main(){
    fprintf(stderr, "MAIN!\n"); 
    return 0;
}

int __wrap_fprintf(FILE *stream, const char *format, ...){
    __real_fprintf(stderr, "WRAP!\n");
    return 0;
}

Upvotes: 4

Views: 610

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126223

If you want this to work properly for fprintf, you need to also add the flag -fno-builtin-fprintf to the command line. Othwise, gcc will optimize the call to fprintf to instead call fwrite, and the linker will not see a call to fprintf to wrap.

In general, to properly wrap any function, you may need the corresponding -fno-builtin- option as well.

Upvotes: 7

Leon
Leon

Reputation: 32484

fprintf without arguments (other than the format string) is optimized to fwrite. Change your call of fprintf to fprintf(stderr, "%s\n", "MAIN!"); and the wrapping will take effect.

int __real_fprintf(FILE *stream, const char *format, ...);

int main(){
    fprintf(stderr, "%s\n", "MAIN!"); 
    return 0;
}

int __wrap_fprintf(FILE *stream, const char *format, ...){
    __real_fprintf(stderr, "WRAP!\n");
    return 0;
}

Upvotes: 3

Related Questions