g ++,静态初始化和-nostdlib

Tho*_*mas 12 gcc g++ static-initialization

编译/链接-nostdlib似乎可以防止静态初始化,即使我用.init/ .finisections 添加我自己的crti.s和crtn.s.

是否有解决方法使g ++生成插入的静态初始化代码.init或我可以手动调用?

这是我试过的:

g++ -o test.o -c -fno-use-cxa-atexit test.cc  # has _start (entry point) 
                                              #   that calls _init and _main
as -o crti.o crti.s      # has _init in section .init
as -o crtn.o crtn.s
g++ -o test ./crti.o test.o -nodefaultlibs -nostartfiles ./crtn.o
Run Code Online (Sandbox Code Playgroud)

-nodefaultlibs 单独包括静态初始化代码和调用,但强制使用libc-_start/_init.

-nodefaultlibs -nostartfiles 允许我使用自己的_start/_init,但不包括代码或调用静态初始化.

Pav*_*ath 11

来自gcc链接器文档,

-nostdlib

链接时请勿使用标准系统启动文件或库.没有启动文件,只有您指定的库将传递给链接器,并且将忽略指定系统库链接的选项,例如-static-libgcc或-shared-libgcc.

因此使用,

-nodefaultlibs

链接时请勿使用标准系统库.只有您指定的库才会传递给链接器,指定系统库链接的选项(例如-static-libgcc或-shared-libgcc)将被忽略.除非使用-nostartfiles,否则标准启动文件将正常使用.编译器可能会生成对memcmp,memset,memcpy和memmove的调用.这些条目通常由libc中的条目解析.指定此选项时,应通过其他机制提供这些入口点.

也试试,

g++ -Wl, -static

-Wl      passes the next command on to the linker
-static  On systems that support dynamic linking, this prevents linking with 
         the shared libraries. On other systems, this option has no effect.
Run Code Online (Sandbox Code Playgroud)