c - GCC 在哪里找到 printf ?我的代码在没有任何 #include 的情况下工作

标签 c

我是 C 语言的初学者,所以我试图破解这些东西。

我阅读了 stdio.h 并找到了这一行: extern int printf (const char *__restrict __format, ...);

所以我写了这段代码,但我不知道它为什么有效。

代码:

extern int printf (const char *__restrict __format, ...);

main()
{
    printf("Hello, World!\n");
}

输出:

sh-5.1$ ./a.out 
Hello, World!
sh-5.1$ 

GCC 在哪里找到函数 printf?它还适用于其他编译器。 我是 C 的初学者,我觉得这很奇怪。

最佳答案

默认情况下,gcc 会将您的程序与实现 printf 的 c 库 libc 链接:

$ ldd ./a.out
        linux-vdso.so.1 (0x00007ffd5d7d3000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fdf2d307000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fdf2d4f0000)

$ nm -D /lib/x86_64-linux-gnu/libc.so.6 | grep ' printf' | head -1
0000000000056cf0 T printf@@GLIBC_2.2.5

如果您使用 -nolibc 构建您的程序,您必须自己满足一些符号(请参阅 Compiling without libc ):

$ gcc -nolibc ./1.c 
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/10/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x12): undefined reference to `__libc_csu_fini'
/usr/bin/ld: (.text+0x19): undefined reference to `__libc_csu_init'
/usr/bin/ld: (.text+0x26): undefined reference to `__libc_start_main'
/usr/bin/ld: /tmp/user/1000/ccCFGFhf.o: in function `main':
1.c:(.text+0xc): undefined reference to `puts'
collect2: error: ld returned 1 exit status

关于c - GCC 在哪里找到 printf ?我的代码在没有任何 #include 的情况下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71759099/

相关文章:

c - 你用什么cscope引用卡?

c - 运行时深奥的 C 程序行为 - 代码未按顺序运行

c++ - 在 C 中导航数组(性能)?

c - yacc/bison 操作的范围是什么?

c++ - 添加断点并运行程序时无法访问地址处的内存

c - 当我想将数组写入文件时内存损坏

C语言 bool 表达式返回值

c - C 中的预处理器命令算作 token 吗?

c - gcc-10.0.1 特定的段错误

c++ - 使用libjpeg写入内存缓冲区而不是文件?