linux系统下多语言适配

本文介绍gettext在类Unix系统中的应用,从包括hello.c示例到生成hello.pot文件,再到手动翻译和自动化过程。重点讲解了如何处理多语言文件和hello.pot文件的维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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!


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值