的C main()函数可以是静态的? [英] Can the C main() function be static?

查看:157
本文介绍了的C main()函数可以是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在的main()函数声明静态在C程序?如果这样的话有什么用呢?

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

是否有可能,如果我使用汇编code和调用静态main()函数自己(考虑嵌入式程序)?

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

推荐答案

没有。的C规格实际上说某处它(我读了规范,信不信由你),主要功能不能是静态的。

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

这样做的原因是,静态的意思是不要让这个源文件使用该对象以外的任何东西。这样做的好处是,它可以防止用C名称冲突,当你去链接(这将是很坏很坏的坏,如果你有两个全局在不同的文件都命名为is_initialized......他们会得到默默地合并,除非你让他们静态的)。它也允许编译器执行某些优化,这将无法以其他方式。这两个原因,为什么静态就是有一个很好的事情。

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.

编辑:看来我错了,该规范主要说不能是静态的,但它确实说,它不能在托管环境内联(如果你要问什么是托管环境的意思,那么你在一个)。但在OS X和Linux,如果你声明主静,那么你会得到一个链接错误,因为链接器找不到主的定义。

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

这篇关于的C main()函数可以是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆