为什么 std::stoi 和 std::array 不能用 g++ c++11 编译?

问题描述 投票:0回答:1

过去几个月我一直在学习 C++ 并使用终端。我的代码使用 g++ 和 C++11 编译并运行良好,但在过去几天里它开始出现错误,从那以后我就遇到了编译问题。我唯一可以编译和运行的程序依赖于较旧的 C++ 标准。

我首先遇到的错误与头文件中的

#include <array>
有关。不知道为什么会发生这种情况,但我通过使用
boost/array
来解决它。我无法解决的另一个错误是
std::stoi
array
stoi
都应该在 C++11 标准库中。我编写了以下简单的代码来演示发生了什么:

//
//  stoi_test.cpp
//
//  Created by ecg
//

#include <iostream>
#include <string> // stoi should be in here

int main() {

    std::string test = "12345";
    int myint = std::stoi(test); // using stoi, specifying in standard library
    std::cout << myint << '\n'; // printing the integer

    return(0);

}

尝试使用

ecg$ g++ -o stoi_trial stoi_trial.cpp -std=c++11

进行编译
> array.cpp:13:22: error: no member named 'stoi' in namespace 'std'; did you mean
>      'atoi'?
>    int myint = std::stoi(test);
>                ~~~~~^~~~
>                     atoi
> /usr/include/stdlib.h:149:6: note: 'atoi' declared here
> int      atoi(const char *);
>         ^
> array.cpp:13:27: error: no viable conversion from 'std::string' (aka
>      'basic_string<char>') to 'const char *'
>    int myint = std::stoi(test);
>                          ^~~~
> /usr/include/stdlib.h:149:23: note: passing argument to parameter here
> int      atoi(const char *);
>                          ^
> 2 errors generated.

当使用 gcc 或 clang++ 以及

-std=gnu++11
时,我也会在编译时遇到这些错误(我猜它们都依赖于相同的文件结构)。无论我在代码中指定
std::
还是指定
using namespace std;

,我也会收到相同的错误

我担心这些问题的出现是因为 9 月份通过 Xcode 进行的命令行工具更新,或者是因为我安装了 boost,这在某种程度上弄乱了我的 C++11 库。希望有一个简单的解决方案。

我的系统:

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-> dir=/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.76) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin12.5.0
Thread model: posix

感谢您提供的任何见解。

c++ macos c++11 g++ std
1个回答
5
投票

clang 有一个奇怪的 stdlib,编译时需要添加以下标志

-stdlib=libc++

你的代码片段可以在我的 Mac 上使用

g++ -std=gnu++11  -stdlib=libc++ test.cpp -o test

这个答案描述了问题

© www.soinside.com 2019 - 2024. All rights reserved.