C ++-Android NDK std :: to_string supp
我正在使用android NDK r9d和工具链4.8,但无法使用std :: to_string函数,编译器会引发以下错误:
error: 'to_string' is not a member of 'std'
android ndk不支持此功能吗? 我尝试APP_CPPFLAGS := -std=c++11
没有运气。
albciff asked 2020-02-20T05:10:49Z
6个解决方案
61 votes
您可以尝试LOCAL_CFLAGS := -std=c++11
,但请注意,并非所有C ++ 11 API都可用于NDK的gnustl。 libc ++(APP_STL := c++_shared
)提供了对C ++ 14的完全支持。
另一种方法是自己实施。
#include <string>
#include <sstream>
template <typename T>
std::string to_string(T value)
{
std::ostringstream os ;
os << value ;
return os.str() ;
}
int main()
{
std::string perfect = to_string(5) ;
}
26 votes
使用NDK r9 +,您可以使用llvm-libc ++,它提供对cpp11的全面支持。
在您的Application.mk中,您必须添加:
APP_STL:=c++_static
要么
APP_STL:=c++_shared
12 votes
摇篮
如果您正在寻找Gradle构建系统的解决方案。 看这个答案。
简短的答案。
添加字符串
arguments "-DANDROID_STL=c++_shared"
在您的build.gradle
中。喜欢
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
...
arguments "-DANDROID_STL=c++_shared"
}
}
}
...
}
1 votes
实验性Gradle插件
如果您正在寻找实验性Gradle插件的解决方案,那么这对我很有用...
使用com.android.tools.build:gradle-experimental:0.9.1测试
model {
...
android {
...
ndk {
...
stl = "c++_shared"
}
}
}
0 votes
我无法使用sources/cxx-stl/llvm-libc++/src/string.cpp
,它给出了有关未定义异常的一些错误。 所以我回到了to_string(int)
。
但是在NDK源中,在sources/cxx-stl/llvm-libc++/src/string.cpp
中,我找到了to_string(int)
的实现,并尝试将其复制到我的代码中。 经过一些更正后,它起作用了。
所以我的最后一段代码是:
#include <string>
#include <algorithm>
using namespace std;
template<typename S, typename P, typename V >
inline
S
as_string(P sprintf_like, S s, const typename S::value_type* fmt, V a)
{
typedef typename S::size_type size_type;
size_type available = s.size();
while (true)
{
int status = sprintf_like(&s[0], available + 1, fmt, a);
if ( status >= 0 )
{
size_type used = static_cast<size_type>(status);
if ( used <= available )
{
s.resize( used );
break;
}
available = used; // Assume this is advice of how much space we need.
}
else
available = available * 2 + 1;
s.resize(available);
}
return s;
}
template <class S, class V, bool = is_floating_point<V>::value>
struct initial_string;
template <class V, bool b>
struct initial_string<string, V, b>
{
string
operator()() const
{
string s;
s.resize(s.capacity());
return s;
}
};
template <class V>
struct initial_string<wstring, V, false>
{
wstring
operator()() const
{
const size_t n = (numeric_limits<unsigned long long>::digits / 3)
+ ((numeric_limits<unsigned long long>::digits % 3) != 0)
+ 1;
wstring s(n, wchar_t());
s.resize(s.capacity());
return s;
}
};
template <class V>
struct initial_string<wstring, V, true>
{
wstring
operator()() const
{
wstring s(20, wchar_t());
s.resize(s.capacity());
return s;
}
};
string to_string(int val)
{
return as_string(snprintf, initial_string<string, int>()(), "%d", val);
}
0 votes
对于Android Studio,将其添加到build.gradle(移动应用程序)中
externalNativeBuild {
cmake {
cppFlags "-std=c++11"
arguments "-DANDROID_STL=c++_static"
}
}