简体   繁体   English

使用 gcc 编译 c 程序,访问 stdlib 函数,但不使用 _start 和所有 libc init 函数

[英]Compile c program with access to stdlib functions, but without _start and all of the libc init functions using gcc

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.所以基本上我想用 gcc 静态编译一个 c 程序,我希望它能够链接 c stdlib 函数,但我希望它从 main 开始,而不包括_start function 以及发生的 libc init 东西在主要之前。 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.通常当你想编译一个没有_start的程序时,你运行带有-nostdlib标志的 gcc,但我希望也能够包含来自 stdlib 的代码,而不是 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.我知道这可能会导致很多问题,但对于我的用例,我实际上并没有运行 c 程序本身,所以这样做是有意义的。

Thanks in advance提前致谢

The option -nostdlib tells the linker to not use the startup files (ie. the code that is executed before the main ).选项-nostdlib告诉 linker 不要使用启动文件(即在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 .您仍然可以通过使用-lc来使用 libc 的功能。 However keep in mind that some of the libc function depend on the startup code.但是请记住,某些 libc function 取决于启动代码。 For example in some implementations printf requires dynamic memory allocation and the heap is initialized by the startup code.例如在某些实现中printf需要动态分配 memory 并且堆由启动代码初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM