Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c preprocessor - Does the program execution always start from main in C?

Must program execution start from main, or can the starting address be modified?

#include <stdio.h>

void fun();

#pragma startup fun

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

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

This program prints in fun before in main.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, The GNU C Preprocessor, version 1.34

Program execution starts at the startup code, or "runtime". This is usually some assembler routine called _start or somesuch, located (on Unix machines) in a file crt0.o that comes with the compiler package. It does the setup required to run a C executable (like, setting up stdin, stdout and stderr, the vectors used by atexit()... for C++ it also includes initializing of global objects, i.e. running their constructors). Only then does control jump to main().

As the quote at the beginning of my answer expresses so eloquently, what #pragma does is completely up to your compiler. Check its documentation. (I'd guess your pragma startup - which should be prepended with a # by the way - tells the runtime to call fun() first...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...