为什么当有换行符时用 ld 包装 printf 会失败?

awe*_*kie 5 c linker gcc ld

我正在尝试拦截对printfusing的ld调用-wrap调用。我有两个文件:

主要.c:

#include <stdio.h>

int main(void) {
    printf("printing\n");
    printf("printing");
}
Run Code Online (Sandbox Code Playgroud)

printf_wrapper.c:

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

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

我使用以下命令进行编译:

gcc -Wl,-wrap,printf *.c
Run Code Online (Sandbox Code Playgroud)

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

printing
WRAPPED
Run Code Online (Sandbox Code Playgroud)

如果字符串中有换行符,为什么换行会失败?我检查了我的系统stdio.h,发现 printf 不是宏。这是 gcc 5.3.0 的情况

bru*_*ceg 2

使用 -fno-builtin 选项告诉 gcc 不要搞乱某些指定的函数。因此,如果您添加 -fno-builtin-printf 它应该可以工作。一般来说,它可能会导致一些本来可以被编译器捕获的问题被遗漏。有关详细信息,请参阅 gcc 文档,例如https://gcc.gnu.org/onlinedocs/gcc-4.2.2/gcc/C-Dialect-Options.html