为啥以下代码在在线 ide(gcc 7.2.0) 上有效,但在 ubuntu 上出错?

Posted

技术标签:

【中文标题】为啥以下代码在在线 ide(gcc 7.2.0) 上有效,但在 ubuntu 上出错?【英文标题】:Why does the following code work on online ide(gcc 7.2.0) but gives error on ubuntu?为什么以下代码在在线 ide(gcc 7.2.0) 上有效,但在 ubuntu 上出错? 【发布时间】:2017-08-18 02:29:25 【问题描述】:

当我在 ubuntu(gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4)) 上运行以下代码时:

#include<iostream>
#include<vector>
#include<list>
using namespace std;
int main()
vector <int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
list<int> temp;
for(auto i:v)
    cout<<i<<" ";
    temp.push_back(i);

for(auto i:temp)
    cout<<i<<" ";


我收到以下错误:

try.cpp: In function ‘int main()’:
try.cpp:13:10: error: ‘i’ does not name a type
 for(auto i:v)
          ^
try.cpp:17:1: error: expected ‘;’ before ‘for’
 for(auto i:temp)
 ^
try.cpp:17:1: error: expected primary-expression before ‘for’
try.cpp:17:1: error: expected ‘;’ before ‘for’
try.cpp:17:1: error: expected primary-expression before ‘for’
try.cpp:17:1: error: expected ‘)’ before ‘for’
try.cpp:17:10: error: ‘i’ does not name a type
 for(auto i:temp)
          ^
try.cpp:20:1: error: expected ‘;’ before ‘’ token
 
 ^
try.cpp:20:1: error: expected primary-expression before ‘’ token
try.cpp:20:1: error: expected ‘;’ before ‘’ token
try.cpp:20:1: error: expected primary-expression before ‘’ token
try.cpp:20:1: error: expected ‘)’ before ‘’ token
try.cpp:20:1: error: expected primary-expression before ‘’ token

但是当我在在线 ide 上运行代码时,我工作正常。代码有什么问题? 在线ide代码链接:No errors

【问题讨论】:

你是如何在 Ubuntu 上编译的? @MichaelAlbers g++ -o try try.cpp 你没有说你在 Ubuntu (gcc --version) 上使用的是什么版本的 gcc,但我敢打赌它已经足够老了,默认情况下它不支持 C++ 11 功能。尝试使用-std=gnu++11 选项。 @MichaelBurr gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609 Copyright (C) 2015 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. @MichaelBurr 我可以升级它吗? 【参考方案1】:

您的代码使用了一些 C++11 功能,例如 range based loops 和 auto specifier,但您没有针对 C++11 标准进行编译。您需要在编译时通过包含 -std=c++11 标志来启用 C++11 支持:

g++ -std=c++11 -o try try.cpp

在线编译器通过使用-std=gnu++1z 标志启用此功能。

【讨论】:

以上是关于为啥以下代码在在线 ide(gcc 7.2.0) 上有效,但在 ubuntu 上出错?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 gcc 的输出比 Visual Studio 慢得多(对于此代码)?

为啥 GCC 会警告这种隐式转换?

为啥结构化绑定在 GCC 上失败?

为啥 GCC 生成的代码会从堆栈中读取垃圾?

有没有办法在 Windows 中托管 IDE,但在 linux 上托管源代码和编译(GCC)? [关闭]

为啥 getResourceAsStream() 可以在 IDE 中工作,但不能在 JAR 中工作?