简体   繁体   English

如何确定默认情况下 gcc 传递给 ld 的命令行选项?

[英]How to determine which command line options gcc passes to ld by default?

Consider the hello world C program:考虑 hello world C 程序:

hello.c :你好.c :

#include "stdio.h"

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

If I call:如果我打电话:

$ gcc -c hello.c -o hello.o

It will produce an ELF Relocatable File hello.o它将产生一个 ELF 可重定位文件hello.o

If I then call:如果我然后打电话:

$ gcc hello.o -o hello            [1]

It will link hello.o with ld and produce an ELF Executable File hello它将 hello.o 与 ld 链接并生成一个 ELF 可执行文件hello

However if I call ld directly [2] instead of [1] :但是,如果我直接调用 ld [2]而不是[1]

$ ld hello.o -o hello             [2]

I get these errors:我收到这些错误:

/usr/bin/ld.bfd.real: warning: cannot find entry symbol _start
test.c:(.text+0xa): undefined reference to `puts'

gcc must be passing other options to ld (to link the C library for example). gcc 必须将其他选项传递给 ld(例如链接 C 库)。

Is there anyway to determine exactly what the command-line gcc is passing through to ld in command [1] ?无论如何要确定命令行 gcc 在命令[1]传递给 ld 的确切内容?

Yes, you can use gcc -v hello.o -o hello to get the link line.是的,您可以使用gcc -v hello.o -o hello来获取链接行。 For your example on my ubuntu machine, I get this link line (edited to be multiline for readability):对于你在我的 ubuntu 机器上的例子,我得到了这个链接行(为了可读性编辑为多行):

/usr/lib/gcc/x86_64-linux-gnu/4.4.5/collect2
--build-id
--eh-frame-hdr
-m elf_x86_64
--hash-style=gnu
-dynamic-linker
/lib64/ld-linux-x86-64.so.2
-o hello
-z relro
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crt1.o
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crti.o
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/crtbegin.o
-L/usr/lib/gcc/x86_64-linux-gnu/4.4.5
-L/usr/lib/gcc/x86_64-linux-gnu/4.4.5
-L/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib
-L/lib/../lib
-L/usr/lib/../lib
-L/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../.. -L/usr/lib/x86_64-linux-gnu
hello.o
-lgcc
--as-needed -lgcc_s --no-as-needed 
-lc
-lgcc
--as-needed -lgcc_s --no-as-needed
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/crtend.o
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crtn.o

Note that collect2 is just an alias for ld .请注意, collect2只是ld的别名。

For oneline lovers:对于在线爱好者:

echo "int main(void) {}" | gcc -o /dev/null -v -x c - &> /dev/stdout| grep collect | tr -s " " "\012"

Replace -xc with -x c++ to get c++ flags.-xc替换为-x c++以获取 c++ 标志。

Can be used also with clang, but in such case you should grep for /usr/bin/ld也可以与 clang 一起使用,但在这种情况下,您应该 grep for /usr/bin/ld

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

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