c ++ boost locale - 生成器抛出 runtime_error 和 "Invalid file format" 消息

c++ boost locale - generator throws runtime_error with "Invalid file format" message

我尝试用这段代码重现 boost locale documentation 的示例:

#include <boost/locale.hpp>

#include <iostream>
#include <stdexcept>

using namespace boost::locale;
using namespace std;

int main()
{
   generator gen;

   // Specify location of dictionaries
   gen.add_messages_path("./languages");
   gen.add_messages_domain("hello");

   // Generate locales and imbue them to iostream
   locale::global(gen("es_ES"));
   cout.imbue(locale());

   // Display a message using current system locale
   cout << translate("Hello World") << endl;
   return 0;
}

我用 xgettext 生成了这个 hello.mo 文件,并将其放在文件夹 ./languages/es_ES/LC_MESSAGES 中:

# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-01-13 17:30+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"

#: test.cpp:95
msgid "Hello World"
msgstr "Hola a todos"

当我 运行 代码时,行 locale::global(gen("es_ES")); 抛出一个 std::runtime_error 和这条消息:“无效的文件格式”。是不是说.mo文件有错误?

我忘了编译.po 文件... xgettext 生成一个.po 文本文件,需要将其编译成.mo 文件。这可以用 msgfmt 来完成:

msgfmt hello.po -o hello.mo