c++ - 是否可以在不使用 main() 函数的情况下编写程序?

标签 c++ c compilation program-entry-point

我在面试中不断被问到这个问题:

不使用 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/

相关文章:

C++ 使用 `.reserve()` 填充 `std::vector` 作为防止多线程缓存失效和错误共享的方法

C 函数指针

java - 如何在 JNI 调用中使用全局引用

c++ - C++程序在后台运行,没有管理员权限

c - 多个定义在 gcc 或 clang 中都不会给出错误或警告

compilation - 我可以将多种语言的代码与 LLVM 一起编译吗?

c++ - 为什么我的程序会在拥有线程的情况下生成 LdrpLoaderLock 死锁?

c++ - 使用非类型模板参数而不是常规参数的原因?

c++ - 拆分后的空 vector

c - 在 C 中将数据读入数组时出错