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.
A static initialization in java is a particular block that is made to run before the main () method in java whereas dynamic initialization refers to the initiation of the project during the rum time.
Static functions can be called directly by using class name. Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function.
Static initialization happens first and usually at compile time. If possible, initial values for static variables are evaluated during compilation and burned into the data section of the executable. Zero runtime overhead, early problem diagnosis, and, as we will see later, safe. This is called constant initialization.
A Static Initialization Block in Java is a block that runs before the main( ) method in Java. Java does not care if this block is written after the main( ) method or before the main( ) method, it will be executed before the main method( ) regardless.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With