Can the C main() function be static?

前端 未结 5 798
北荒
北荒 2021-01-01 17:00

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

5条回答
  •  囚心锁ツ
    2021-01-01 17:08

    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".

提交回复
热议问题