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

2022-01-04 00:00:00 main compilation c c++

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

I keep getting this question asked in interviews:

不使用main()函数编写程序?

Write a program without using main() function?

我的一个朋友向我展示了一些使用宏的代码,但我无法理解.

One of my friends showed me some code using Macros, but i could not understand it.

所以问题是:

没有main()真的可以编写和编译程序吗?

Is it really possible to write and compile a program without main()?

推荐答案

在标准 C++ 中需要一个 main 函数,所以这个问题对标准 C++ 没有意义.

Within standard C++ a main function is required, so the question does not make sense for standard C++.

在标准 C++ 之外,您可以例如编写 Windows 特定程序并使用 Microsoft 的自定义启动函数之一(wMain、winMain、wWinmain).在 Windows 中,您也可以将程序编写为 DLL 并使用 rundll32 来运行它.

Outside of standard C++ you can for example write a Windows specific program and use one of Microsoft's custom startup functions (wMain, winMain, wWinmain). In Windows you can also write the program as a DLL and use rundll32 to run it.

除此之外,您还可以制作自己的小型运行时库.曾几何时,这是一项常见的运动.

Apart from that you can make your own little runtime library. At one time that was a common sport.

最后,您可以聪明地反驳说,根据标准的 ODR 规则 main 未被使用",因此任何程序都符合条件.呸!尽管除非面试官有不同寻常的幽默感(如果有的话,他们也不会问这个问题),否则他们不会认为这是一个很好的答案.

Finally, you can get clever and retort that according to the standard's ODR rule main isn't "used", so any program qualifies. Bah! Although unless the interviewers have unusual good sense of humor (and they wouldn't have asked the question if they had) they'll not think that that's a good answer.

相关文章