gpt4 book ai didi

c - 检测 -nostdlib 或仅检测 stdlib 是否可用

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:00 26 4
gpt4 key购买 nike

我的家庭作业要求我们使用系统调用而不是标准库来打开、读取和写入文件。为了调试它,我想在测试编译项目时使用 std 库。我这样做了:

#ifdef HOME
//Home debug prinf function
#include <stdio.h>
#else
//Dummy prinf function
int printf(const char* ff, ...) {
return 0;
}
#endif

我这样编译它:gcc -DHOME -m32 -static -O2 -o main.exe main.c

问题是我使用 -nostdlib 参数,标准入口点是 void _start 但没有参数,入口点是 int main(const char ** 参数)。你可能会这样做:

//Normal entry point
int main(const char** args) {
_start();
}
//-nostdlib entry point
void _start() {
//actual code
}

在这种情况下,这就是在没有 -nostdlib 的情况下进行编译时得到的结果:

/tmp/ccZmQ4cB.o: In function `_start':
main.c:(.text+0x20): multiple definition of `_start'
/usr/lib/gcc/i486-linux-gnu/4.7/../../../i386-linux-gnu/crt1.o:(.text+0x0): first defined here

因此我需要检测是否包含 stdlib,并且在这种情况下不定义 _start

最佳答案

对于您的系统,低级入口点始终是 _start。使用 -nostdlib,它的定义在链接中被省略,因此您必须提供一个。如果没有 -nostdlib,您不能尝试定义它;即使这没有从重复定义中得到链接错误,它也会可怕地破坏标准库运行时的启动。

相反,尝试以相反的方式进行:

int main() {
/* your code here */
}
#ifdef NOSTDLIB_BUILD /* you need to define this with -D */
void _start() {
main();
}
#endif

您可以选择向 main 添加假参数。但是,不可能从用 C 编写的 _start 中获得真实的。为此,您需要在 asm 中编写 _start

请注意 -nostdlib 是一个链接器选项,而不是编译时选项,因此无法在编译时自动确定-nostdlib 将被使用。相反,只需制作您自己的宏并将其作为 -DNOSTDLIB_BUILD 或类似的形式在命令行上传递。

关于c - 检测 -nostdlib 或仅检测 stdlib 是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29495356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com