如何使用本地操作系统环境使用gettetxt()初始化静态char *?

时间:2009-07-11 22:17:19

标签: c++ linux internationalization gettext

C ++中是否有标准或通用的方法来处理需要由gettext()设置的静态字符串?

以下示例使用Complete C++ i18n gettext() “hello world” example的答案作为基础,只是将文字hello world更改为静态char* hwschar* hw。 在设置语言环境之前,hws似乎已初始化为默认的英语文本 本地操作系统环境。虽然在更改语言环境后设置了hw,因此生成了西班牙语文本。

cat >hellostaticgt.cxx <<EOF
// hellostaticgt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
char* hws = gettext("hello, world static!");
int main (){
    setlocale(LC_ALL, "");
    bindtextdomain("hellostaticgt", ".");
    textdomain( "hellostaticgt");
    char* hw = gettext("hello, world!");
    std::cout << hws << std::endl;
    std::cout << hw << std::endl;
}
EOF
g++ -o hellostaticgt hellostaticgt.cxx
xgettext --package-name hellostaticgt --package-version 1.0 --default-domain hellostaticgt --output hellostaticgt.pot hellostaticgt.cxx
msginit --no-translator --locale es_MX --output-file hellostaticgt_spanish.po --input hellostaticgt.pot
sed --in-place hellostaticgt_spanish.po --expression='/#: /,$ s/""/"hola mundo"/'
mkdir --parents ./es_MX.utf8/LC_MESSAGES
msgfmt --check --verbose --output-file ./es_MX.utf8/LC_MESSAGES/hellostaticgt.mo hellostaticgt_spanish.po
LANGUAGE=es_MX.utf8 ./hellostaticgt

2 个答案:

答案 0 :(得分:1)

您需要将gettext用法分为两部分。首先,您只需使用宏标记字符串,例如gettext_noop,以便xgettext将其提取出来。然后,当您引用全局变量时,使用true gettext调用来包装访问。

请参阅gettext手册中的Special Cases

N.B。你的变量hws不是静态变量(没有“静态关键字”);它是一个全局变量。

答案 1 :(得分:0)

这是应用answer from Martin v. Löwis后的代码:

cat >hellostaticgt.cxx <<EOF
// hellostaticgt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
#define gettext_noop(S) S
const char* hws_eng = gettext_noop("hello, world static!");
int main (){
    setlocale(LC_ALL, "");
    bindtextdomain("hellostaticgt", ".");
    textdomain( "hellostaticgt");
    char* hw = gettext("hello, world!");
    std::cout << gettext(hws_eng) << std::endl;
    std::cout << hw << std::endl;
}
EOF
g++ -o hellostaticgt hellostaticgt.cxx
xgettext --package-name hellostaticgt --package-version 1.0 --default-domain hellostaticgt --output hellostaticgt.pot hellostaticgt.cxx
msginit --no-translator --locale es_MX --output-file hellostaticgt_spanish.po --input hellostaticgt.pot
sed --in-place hellostaticgt_spanish.po --expression='/"hello, world static!"/,/#: / s/""/"hola mundo static"/'
sed --in-place hellostaticgt_spanish.po --expression='/"hello, world!"/,/#: / s/""/"hola mundo"/'
mkdir --parents ./es_MX.utf8/LC_MESSAGES
msgfmt --check --verbose --output-file ./es_MX.utf8/LC_MESSAGES/hellostaticgt.mo hellostaticgt_spanish.po
LANGUAGE=es_MX.utf8 ./hellostaticgt

结果具有所需和预期的输出:

hola mundo static
hola mundo