Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are std::stoi and std::array not compiling with g++ c++11?

I've been learning C++ and using the Terminal for the last couple of months. My code was compiling and running fine using g++ and C++11, but in the last couple of days it started giving errors and I have had problems compiling since. The only programs I can compile and run depend on older C++ standards.

The errors I first got related to #include < array > in the header file. Not sure why this happened, but I got around it by using boost/array instead. Another error I can't solve is with std::stoi. Both array and stoi should be in the C++11 standard library. I made the following simple code to demonstrate what's going on:

//
//  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);

}

Try to compile using 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') 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.

I also get these errors at compilation when using gcc or clang++ and with -std=gnu++11 (I guess they all depend on the same file structure). I also get the same error whether I specify std:: in the code, or if I specify using namespace std;

I worry that these issues arose because of the September Command Line Tools update via Xcode or because I installed boost and this somehow messed up my C++11 libraries. Hopefully there is a simple solution.

My system:

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

Thanks for any insight you can offer.

like image 384
user2865112 Avatar asked Oct 10 '13 01:10

user2865112


1 Answers

clang has a weird stdlib, you need to add the following flag when you compile

-stdlib=libc++

your snippet works on my mac with

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

This answer describes the problem

like image 120
pyCthon Avatar answered Sep 19 '22 11:09

pyCthon