c - 程序执行是否总是从 C 中的 main 开始?

标签 c c-preprocessor pragma preprocessor-directive

程序执行必须从main开始,还是可以修改起始地址?

#include <stdio.h>

void fun();

#pragma startup fun

int main()
{
    printf("in main");
    return 0;
}

void fun()
{
    printf("in fun");
}

该程序打印 in fun之前 in main .

最佳答案

The '#pragma' command is specified in the ANSI standard to have an arbitrary implementation-defined effect. In the GNU C preprocessor, '#pragma' first attempts to run the game 'rogue'; if that fails, it tries to run the game 'hack'; if that fails, it tries to run GNU Emacs displaying the Tower of Hanoi; if that fails, it reports a fatal error. In any case, preprocessing does not continue.



-- Richard M. Stallman,GNU C 预处理器,版本 1.34

程序执行从启动代码或“运行时”开始。这通常是一些名为 _start 的汇编程序。或类似的,位于(在 Unix 机器上)文件中 crt0.o随编译器包一起提供。它执行运行 C 可执行文件所需的设置(例如,设置 stdinstdoutstderratexit() 使用的 vector ... 对于 C++ 它还包括全局对象的初始化,即运行它们的构造函数)。只有这样控制才会跳转到main()。 .

正如我的答案开头的引述如此 Eloquent 地表达的那样,#pragma是否完全取决于您的编译器。检查其文档。 (我猜你的 pragma startup - 应该在前面加上 # - 告诉运行时首先调用 fun()...)

关于c - 程序执行是否总是从 C 中的 main 开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6897763/

相关文章:

gcc - 即使它真的是.c,如何告诉GCC输入文件是汇编程序?

c - 在特定内存中定位c库函数

c - 哪个文件应包含我的 c 项目中的库?

c++ - 如何将 C++ 宏转换为 typedef?

难道我们不能为#define写一个可执行语句吗?

c++ - GCC 没有矢量化输出?

database - 在 Lua 中更新数据库版本

c++ - 为什么 system() 失败并显示错误代码 127?

c - 如何从标准输入确定二维数组的高度和长度?

C++预处理器##运算符