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

后端 未结 2 392
半阙折子戏
半阙折子戏 2020-12-31 13:24

Consider the hello world C program:

hello.c:

#include \"stdio.h\"

int main()
{
        printf(\"Hello, World!\\n\");
}
相关标签:
2条回答
  • 2020-12-31 13:55

    Yes, you can use gcc -v hello.o -o hello to get the link line. For your example on my ubuntu machine, I get this link line (edited to be multiline for readability):

    /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.

    0 讨论(0)
  • 2020-12-31 14:00

    For oneline lovers:

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

    Replace -x c with -x c++ to get c++ flags.

    Can be used also with clang, but in such case you should grep for /usr/bin/ld

    0 讨论(0)
提交回复
热议问题