【发布时间】:2013-09-30 02:03:45
【问题描述】:
我这里有一个简单的 C++ 程序:
#include <iostream>
using namespace std;
main () //no return type for main. Yet program compiles and runs ok
{ //when run by itself.
cout << "hi";
}
但是如果我在另一个名为 newsimpletest1.cpp 的文件中添加空白单元测试,程序将不再编译:
#include <stdlib.h>
#include <iostream>
int main(int argc, char** argv) {
}
如果我运行它,它会按预期编译并打印“hi”。但是如果我测试这个项目,我会得到一个错误:
error: ISO C++ forbids declaration of `__nomain' with no type
当我将返回类型“int”添加到“main”时,它会正确编译并运行。我试图弄清楚这个错误试图告诉我什么。
我正在使用 Windows XP 编译 Netbeans 7.1.2,使用默认的 g++ 编译器。
【问题讨论】:
-
错误信息应该更清楚一点。应该是
... with no return type。 -
您使用的是哪个操作系统和编译器?您的第一个代码 sn-p 不符合标准 C++。第二个代码块不是第一个代码块的测试! (它们完全不相关)。
-
单元测试是否在另一个文件中?名称 main 不得重载(C++ § 3.6.1:2)。此外,单元测试中的 main 没有返回值。这是消息反映的错误。
-
如果 main 没有返回
int,那么你有一个格式错误的程序并且行为是未定义的。任何事情都有可能发生。您的程序可能会崩溃,或者它可能会像没有任何问题一样运行。当您的 main 不返回 int 时会发生以下情况:stackoverflow.com/questions/8844915/… -
@EricLeschinski "Ill-formed" 不会以未定义的行为呈现程序。
标签: c++