The following code works fine on Linux but throws an exception on OS X 10.7:
#include <iostream>
#include <locale>
#include <stdexcept>
int main() try {
std::locale::global(std::locale(""));
std::cout << "Using locale: " << std::locale().name() << "\n";
}
catch (std::runtime_error const& e) {
std::cout << e.what() << "\n";
return 1;
}
The output on OS X is:
locale::facet::_S_create_c_locale
name not valid
However, the standard explicitly says that
The set of valid string argument values is
"C"
,""
, and any implementation-defined values.
So whatever causes the behaviour above is violating the standard.
The compiler used is clang++ 3.1 (tags/Apple/clang-318.0.58); I’ve also tried it with GCC 4.7, installed via Homebrew, with the same result.
Can other people validate this problem? What causes it? Am I doing anything wrong? Is this a bug in OS X?
(Maybe this relates to another xlocale
problem but the errors are actually completely different.)
I don't think you're using xlocale. I believe that your problem is with libstdc++, which uses a different locale support library that is not supported on OS X, as the question EitanT links to states.
If you switch to libc++ your program will work.
The poster above it correct...the problem is with libstdc++. I wanted to add my answer because it is not straightforward how to get OS X to link against libc++ and took me over an hour to figure out.
Invoking the compiler/linker by g++ -libstd=libc++
or by clang++ -libstd=libc++
or by the alias c++ -libstd=libc++
will all fail.
The solution for compiling simple programs from the command line instead of messing with the added overhead of Xcode is to allow Xcode to handle the linking by using the command xcrun clang++ -stdlib=libc++
xcrun
allows Xcode to manage the tool chain and will build a successful executable where cout.imbue(locale(foo))
will successfully work.
来源:https://stackoverflow.com/questions/11190072/setting-locales-on-os-x-crashes