我有一些在 Mac OS X 上运行的代码无法在运行 Linux Mint 的虚拟机上编译。这是一个简单的例子。当我在 Mac 上运行它时,一切都很好,但是当我在 Linux 上运行相同的代码时我遇到了问题,所以我假设我包含的库不存在,但是我应该得到包含错误吗?
这是在 Mac 上运行的示例代码。
#include <iostream>
#include <stdlib.h>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
for (int i = 0; i < 10; i++){
string test = to_string(i);
cout << test << endl;
}
cout << "done" << endl;
return 0;
}
我在这里没有遇到任何问题,但是在 Linux Mint 上运行,我在尝试编译时得到了这个:
for.cpp: In function 'int main()':
for.cpp:7:28 error: 'to_string' was not declared in this scope
string test = to_string(i);
^
make: *** [for] Error 1
我错过了什么吗?任何帮助将非常感激!
编辑
我意识到我忘了包含 <string>
在这里,我修复了它,但我更改的内容(包括 <string>
)仍然无法在 Linux 上编译。我用过 to_string
前。我对 C++ 了解很多。我也尝试添加 <cstdlib>
.再一次,这不会在 Mac 上编译,但不会在 Linux 上编译。
这是我的 OSX 输出:
0
1
2
3
4
5
6
7
8
9
done
这是我在 Linux Mint 上的输出(再一次,Virtual Box,g++ make):
test.cpp: In function ‘int main()’:
test.cpp:9:28: error: ‘to_string’ was not declared in this scope
string test = to_string(i);
^
make: *** [test] Error 1
如果您不相信我,您可以自己重现该问题。都是一样的代码,大家自己看吧。
最佳答案
编译你的for.cpp
像这样的文件:
g++ -std=c++11 for.cpp
并运行它:
./a.out
支持 to_string
<string>
中的函数header 是在 C++11 版本的语言中添加的,所以你需要告诉 GCC 使用那个版本。您可以使用 c++0x
也标记,例如:
g++ -std=c++0x for.cpp
而且您不必担心 <cstdlib>
,这与它无关......
to_string()
在 <string>
中定义如果您使用 C++11 进行编译(但未定义,或者不可靠地定义为扩展功能,如果您使用早期版本的 C++ 进行编译)。
引用:http://en.cppreference.com/w/cpp/string/basic_string/to_string
关于c++ - 无法在 Linux 上运行 to_string() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28919265/