gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:24:01 26 4
gpt4 key购买 nike

我是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com