Can the C main() function be static?

2019-02-12 01:27发布

问题:

Can the main() function be declared static in a C program? If so then what is the use of it?

Is it possible if I use assembly code and call the static main() function myself (consider embedded programs)?

回答1:

No. The C spec actually says somewhere in it (I read the spec, believe it or not) that the main function cannot be static.

The reason for this is that static means "don't let anything outside this source file use this object". The benefit is that it protects against name collisions in C when you go to link (it would be bad bad bad if you had two globals both named "is_initialized" in different files... they'd get silently merged, unless you made them static). It also allows the compiler to perform certain optimizations that it wouldn't be able to otherwise. These two reasons are why static is a nice thing to have.

Since you can't access static functions from outside the file, how would the OS be able to access the main function to start your program? That's why main can't be static.

Some compilers treat "main" specially and might silently ignore you when you declare it static.

Edit: Looks like I was wrong about that the spec says main can't be static, but it does say it can't be inline in a hosted environment (if you have to ask what "hosted environment" means, then you're in one). But on OS X and Linux, if you declare main static, then you'll get a link error because the linker can't find the definition of "main".



回答2:

You could have a static function called main() in a source file, and it would probably compile, but it would not be the main() function because it would be invisible to the linker when the start-up code (crt0.o on many (older) Unix systems) calls main().

Given the code:

static int main(int argc, char **argv)
{
    return(argv + argc);
}

extern int x(int argc, char **argv)
{
    return(main(argc, argv));
}

GCC with -Wall helpfully says:

 warning: 'main' is normally a non-static function

Yes, it can be done. No, it is normally a mistake - and it is not the main() function.



回答3:

No you cannot do it. If you will do it you will be unable to compile your program. Because static function is only visible within the same file, so the linker will no be able to find it and make a call of it.



回答4:

As others have said, no it can't. And that goes double if you ever intend to port your code to C++, as the C++ Standard specifies that main() need not actually be a function.



回答5:

C has two meanings for 'static'...

static for a local variable means it can be used globally. static for a global variable means is can only be used in the current file.

static for functions has the exact same impact as denoting a global variable as static ... the static function IS ONLY VISIBLE IN THE CURRENT FILE ...

Thus main can NEVER be static, because it would not be able to serve as the primary entry point for the program.



标签: c static linker