简体   繁体   English

为什么gcc / clang默认知道链接到libc?

[英]Why does gcc/clang know to link to libc by default?

When I run clang/gcc to compile a .c file, I don't need to explicitly link to libc. 当我运行clang / gcc编译.c文件时,不需要显式链接到libc。 But it still works as libc and two additional libraries are automatically linked. 但是它仍然可以像libc一样工作,并且自动链接了另外两个库。 Why does gcc/clang know to link automatically? 为什么gcc / clang知道自动链接? Where is this behavior mentioned? 在哪里提到这种行为?

$ cat main.c 
/* vim: set noexpandtab tabstop=2: */
#include <stdio.h>

int main() {
    puts("Hello World!");
    return 0;
}
$ clang -o main.exe main.c # or gcc
$ ./main.exe 
Hello World!
$ nm -D /lib/x86_64-linux-gnu/libc-2.27.so | grep -w puts
00000000000809c0 W puts
$ ldd main.exe 
    linux-vdso.so.1 (0x00007ffe743ba000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f397ce7b000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f397d26c000)

Why does gcc/clang know to link automatically? 为什么gcc / clang知道自动链接?

The GCC developers built this into GCC as a convenience. 为了方便起见,GCC开发人员将此内置到GCC中。 Which libraries are linked by default is partly affected by the language being compiled, which is deduced from the file names and may be controlled with the -x switch. 缺省情况下,链接哪些库受编译语言的部分影响,该语言是从文件名推导出的,并且可以使用-x开关进行控制。

Where is this behavior mentioned? 在哪里提到这种行为?

This page in the GCC documentation mentions there are some libraries linked in by default and says you can disable or modify this behavior with -nostdlib and other switches, but I do not see an explicit list of the libraries that are linked in by default. GCC文档中的此页面提到默认情况下有一些链接的库,并说您可以使用-nostdlib和其他开关禁用或修改此行为,但是我看不到默认情况下链接的库的明确列表。 It might vary by system/platform as well as by language. 它可能因系统/平台以及语言而异。 You can use the -v switch to ask GCC to show you the commands it is executing, and the link command (using ld ) should reveal the libraries. 您可以使用-v开关要求GCC向您显示其正在执行的命令,而链接命令(使用ld )应显示库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM