gettext是一种国际化与本地化系统,在类Unix系统中编写多语言程序时经常被使用
#include <stdio.h>
#include <locale.h>
#include <libintl.h>
int main()
{
setlocale(LC_ALL,"");
bindtextdomain("hello","language");
textdomain("hello");
printf(gettext("hello world!\n"));
return 0;
}
xgettext -a hello.c -o hello.pot
生成 hello.pot文件
手动加入手动翻译
据说还能自动加入翻译 这里我就不研究了
生成的 hello.pot文件如下
cat hello.pot
# 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.
#
#: hello.c:7
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-06-28 17:29+0800\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"
#: hello.c:8 hello.c:9
msgid "hello"
msgstr ""
#: hello.c:8
msgid "language"
msgstr ""
#: hello.c:11
#, c-format
msgid "hello world!\n"
msgstr ""
比如我们要给hello world!\n加中文注释的话
cat hello.pot
# 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.
#
#: hello.c:7
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-06-28 17:29+0800\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=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: hello.c:8 hello.c:9
msgid "hello"
msgstr ""
#: hello.c:8
msgid "language"
msgstr ""
#: hello.c:11
#, c-format
msgid "hello world!\n"
msgstr "你好世界!\n"
通过hello.pot再生成hello.po文件
[root@localhost test]# msginit --no-translator --locale=zh_CN.utf-8 --output=hello.po --input=hello.pot
hello.pot: 警告:字符集“UFT-8”不是可移植的编码名称。
将消息转换为用户字符集可能不工作。
已创建 hello.po。
再生成二进制的hello.mo
[root@localhost test]# msgfmt -o hello.mo hello.po
当前目录创建language/zh_CN/LC_MESSAGES/文件夹 把刚生成的hello.mo拷到这里
[root@localhost ptest]# gcc -o hello hello.c
[root@localhost ptest]# echo $LANGUAGE
zh_CN
[root@localhost ptest]# ./hello
你好,世界!
[root@localhost ptest]# export LANGUAGE=en_US
[root@localhost ptest]# ./hello
hello world!