摘要:似乎 C++ std::locale 函数只能在 MacOS 终端应用程序中正常工作,而在捆绑在 MacOS 应用程序捆绑包中时则不能正常工作。
我在MacOS High Sierra上编写了一个使用C++17 std::locale函数的C++应用程序。
对于大多数程序,我想要已经设置的默认"C"语言环境。 但是,对于特殊情况,我想将该类的流输出设置为使用系统区域设置。
当我从命令行运行时,它在测试中效果很好,但是当我将应用程序打包到具有以下结构的MacOS"应用程序包"中时:
MyApp.app/Contents/MacOS/MyApp
然后它无法正常工作。
看起来好像在MacOS 终端应用程序中设置的 LANG 环境变量不是为 MacOS 捆绑包应用程序设置的。
#include <iostream>
#include <fstream>
#include <sstream>
void test( std::ostream &output_, int test_, bool useLocale_, const std::string &expected_ )
{
int i = 1234;
std::stringstream ss;
if ( useLocale_ )
{
ss.imbue( std::locale( "" ) );
}
ss << i;
if ( ss.str( ) == expected_ )
{
output_ << "Test " << test_ << ": Passed" << std::endl;
}
else
{
output_ << "Test " << test_ << ": Expected '" << expected_ << "' but got '" << ss.str( ) << "'" << std::endl;
}
}
int main( )
{
std::ofstream output( "/Users/david/test.txt" );
test( output, 1, false, "1234" );
test( output, 2, true, "1,234" );
return 0;
}
预期结果(以及从 MacOs 终端运行时获得的结果):
Test 1: Passed
Test 2: Passed
但是,双击MacOS MyApp.app 图标时我得到的:
Test 1: Passed
Test 2: Expected '1,234' but got '1234'
所以问题是:如何让 MacOS 捆绑包应用程序将 LANG 环境变量设置为与 MacOS 终端应用程序正在使用的相同内容,或者完成相同操作的其他解决方法?
我花了几天时间在互联网上搜索答案,并看到了一些相关问题,但没有一个直接与我的问题相匹配。
如何为 MacOS 捆绑应用程序设置 LANG 或以其他方式获取系统区域设置?
编辑:我做了更多的测试,问题是LAG环境变量没有在捆绑的应用程序上设置。
所以现在的问题可能归结为:如何在不设置 LANG 环境变量的情况下从 MacOS 系统获取 LANG 信息?
谢谢。
这解决了我的问题。
#ifdef __APPLE__
// MACOS needs a special routine to get the locale for bundled applications.
if ( getenv( "LANG" ) == nullptr )
{
const char *lang = get_mac_locale( );
setenv( "LANG", lang, 1 );
}
#endif
现在我的程序从Apple终端和捆绑应用程序正确运行。