g++, static initialization and -nostdlib

蓝咒 提交于 2019-12-18 02:42:40

问题


Compiling / linking with -nostdlib seems to prevent static initialization, even if I add my own crti.s and crtn.s with .init/.fini sections.

Are there workarounds to make g++ generate static initialization code that is inserted in .init or that I can call manually?

This is what I tried:

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

-nodefaultlibs alone includes static initialization code and call, but forces use of libc-_start/_init.

-nodefaultlibs -nostartfiles allows me to use my own _start / _init, but does not include code or call to static initialization.


回答1:


From gcc linker docs,

-nostdlib

Do not use the standard system startup files or libraries when linking. No startup files and only the libraries you specify will be passed to the linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored.

Hence use,

-nodefaultlibs

Do not use the standard system libraries when linking. Only the libraries you specify will be passed to the linker, options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, will be ignored. The standard startup files are used normally, unless -nostartfiles is used. The compiler may generate calls to memcmp, memset, memcpy and memmove. These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.

Also try,

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.


来源:https://stackoverflow.com/questions/10119520/g-static-initialization-and-nostdlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!