Mac上使用C++ 11标准编译程序

《C++ Primer 5e》是基于C++ 11的标准写的,相比于之前的标准添加了许多新的特性,比如范围for循环。Mac上默认的C++编译器是Clang,我们可以在终端查看。

$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

下面我们写一段需要使用C++ 11特性的程序,这里就用范围for循环:

// range_for.cpp
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char const *argv[])
{
    vector<int> v{1,2,3,4,5,6,7,8,9};
    for (auto &i : v)
        i *= i;
    for (auto &i : v)
        cout << i << " ";
    cout << endl;
    return 0;
}

直接编译g++ range_for.cpp会出现错误和警告

这里写图片描述

我们需要添加-std=c++11才能正常编译,
$ g++ -std=c++11 range_for.cpp
运行编译后的结果$ ./a.out可以得到正确的输出:
1 4 9 16 25 36 49 64 81

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值