How does gcc `-shared` option affect the output?

后端 未结 2 767
臣服心动
臣服心动 2021-01-03 02:38

Technically, in terms of file content, what is the difference between the output of gcc -fPIC -shared src.c and gcc -fPIC src.c?

Assume tha

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 03:10

    Shared libraries and executables use the same format: they are both loadable images. However,

    1. Shared libraries are usually position-independent, executables are often not. This affects code generation: for position-independent, you have to load globals or jump to functions using relative addresses.

    2. Executables have an "entry point" which is where execution starts. This is usually not main(), because main() is a function, and functions return, but execution should never return from the entry point.

    Now, this doesn't answer the question about what -shared does. You can ask GCC by using the -v flag. Here are the differences on my system between an invocation without and with -shared.

    Parameters for collect2 without -shared:

    -dynamic-linker
    /lib64/ld-linux-x86-64.so.2
    /usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o
    /usr/lib/gcc/x86_64-linux-gnu/4.7/crtbegin.o
    /usr/lib/gcc/x86_64-linux-gnu/4.7/crtend.o
    

    Parameters for collect2 with -shared:

    -shared
    /usr/lib/gcc/x86_64-linux-gnu/4.7/crtbeginS.o
    /usr/lib/gcc/x86_64-linux-gnu/4.7/crtendS.o
    

    Observations

    It looks like code generation is not affected: you still have to use -fpic or -fPIC.

    You can see that crt1.o (the "C runtime") is only included when linking the executable. Using nm, we can find out what it contains:

    $ nm /usr/lib/x86_64-linux-gnu/crt1.o
    0000000000000000 R _IO_stdin_used
    0000000000000000 D __data_start
                     U __libc_csu_fini
                     U __libc_csu_init
                     U __libc_start_main
    0000000000000000 T _start
    0000000000000000 W data_start
                     U main
    

    So you can see it seems to define something to do with stdin, as well as _start (which is the entry point), and it has an undefined reference to main.

    I'm not sure what the rest of the files are, but at least you know how to find them and you can poke around, or look at the source code if you like.

提交回复
热议问题