So essentially I want to compile a c program statically with gcc, and I want it to be able to link c stdlib functions, but I want it to start at main, and not include the _start
function as well as the libc init stuff that happens before main. Normally when you want to compile a program without _start
, you run gcc with the -nostdlib
flag, but I want to also be able to include code from stdlib, just not the libc init. Is there any way to do this?
I know that this could cause a lot of problems, but for my use case I'm not actually running the c program itself so it makes sense to do this.
Thanks in advance
CodePudding user response:
The option -nostdlib
tells the linker to not use the startup files (ie. the code that is executed before the main
).
-nostdlib Do not use the standard system startup files or libraries when linking. No startup files and only the libraries you specify are passed to the linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored. 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.
It is frequent to use this option in low-level bare-metal programming in order to control exactly what is going on.
You can still use the functions of your libc by using -lc
. However keep in mind that some of the libc function depend on the startup code. For example in some implementations printf
requires dynamic memory allocation and the heap is initialized by the startup code.