我在面试中不断被问到这个问题:
不使用 main()
函数编写程序?
我的一个 friend 给我看了一些使用宏的代码,但我看不懂。
所以问题是:
真的可以不用main()
来编写和编译程序吗?
最佳答案
不,除非您在 独立环境
(嵌入式环境 OS 内核等)中编写程序,否则您不能以 main()
为起点。根据 C++ 标准,main()
是 托管环境
中任何程序的起点。
根据:
C++03标准3.6.1主函数
1 A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [ Note: In a freestanding environment, start-up and termination is implementation-defined; startup contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration.
什么是独立环境
和什么是托管环境
?
C++ 标准中定义了两种符合标准的实现; 托管
和独立
。
独立
实现是专为在没有操作系统优势的情况下执行的程序而设计的。
例如:操作系统内核或嵌入式环境将是一个独立的环境。
使用操作系统功能的程序通常位于托管实现
中。
来自 C++03 标准第 1.4/7 节:
A freestanding implementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that includes certain language-support libraries.
进一步,
部分:17.4.1.3.2 独立实现引用:
A freestanding implementation has an implementation-defined set of headers. This set shall include at least the following headers, as shown in Table:
18.1 Types <cstddef>
18.2 Implementation properties <limits>
18.3 Start and termination <cstdlib>
18.4 Dynamic memory management <new>
18.5 Type identification <typeinfo>
18.6 Exception handling <exception>
18.7 Other runtime support <cstdarg>
关于c++ - 是否可以在不使用 main() 函数的情况下编写程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7050925/