为什么在换行时用ld包装printf会失败?

时间:2016-03-02 17:26:06

标签: c gcc linker ld

我尝试使用printf ld选项拦截对-wrap的来电。我有两个文件:

main.c中:

#include <stdio.h>

int main(void) {
    printf("printing\n");
    printf("printing");
}

printf_wrapper.c:

int __real_printf(const char *format, ...);

int __wrap_printf(const char *format, ...) {
    (void)format;
    return __real_printf("WRAPPED\n");
}

我用以下命令编译:

gcc -Wl,-wrap,printf *.c

当我运行生成的a.out二进制文件时,我得到了这个输出:

printing
WRAPPED

如果字符串中有换行符,为什么换行会失败?我查看了我的系统stdio.h,而printf不是一个宏。这是使用gcc 5.3.0

1 个答案:

答案 0 :(得分:2)

使用-fno-builtin选项告诉gcc不要乱用某些指定的函数。所以,如果你添加-fno-builtin-printf它应该工作。通常,它可能会导致编译器错过的一些问题。有关详细信息,请参阅gcc文档,例如https://gcc.gnu.org/onlinedocs/gcc-4.2.2/gcc/C-Dialect-Options.html