代码在 ideone 中编译,但不使用 gcc

Code compiles in ideone but not with gcc

本文关键字:gcc ideone 编译 代码      更新时间:2023-10-16

我写了以下代码:

#include <iostream>
using namespace std;
int main()
{
    int v()
    return 0;
}

我在 ideone 中运行了它,它编译成功。我的计算机上的文件test1.cpp中具有相同的代码,我运行g++ test1.cpp并收到以下错误:

./test1.cpp: In function ‘int main()’:
./test1.cpp:7:2: error: a function-definition is not allowed here before ‘return’

为什么会这样?这是一个错误吗?我正在使用 linux mint,gcc 版本 4.7。

您在此处缺少分号:

 int v()
        ^

应该是:

 int v() ;

这是一个函数声明,不清楚这是意图。如果要初始化v则以下方法有效:

 int v(0) ;

或在 C++11 中:

 int v{0} ; 

通常被称为C++最烦人的解析。当你做类似的事情时

int f();

编译器将其读取为函数原型,声明返回int的函数f。如果您使用的是 C++11,则应改为

int f{}; // f initialized to 0

如果不使用 C++11,请确保立即初始化变量。

你忘记了后面的分号

int v();

Ideone 在使用 4.7 时将 gcc 4.8.1 用于您的代码(如您在自己的链接中看到的那样)

关于C++ 11 实现存在一些差异,显然它受到看起来像函数delcaration的行的影响。