這是來自《Free/Open Source Software Guide to Localization》裡面Chapter10的示例,簡單明了,我在RedHat5.3上嘗試了一把,終于明白了gettext的使用方法,雖然還很淺顯哈哈,但對我來說意義非凡!小弟一直想整個可以随便國際化本地化的程式,不知道如何入手,《Free/Open Source Software Guide to Localization》給了我相當的指導,推薦大家閱讀O(∩_∩)O~
廢話不說,直接上代碼,helloworldintl.c:
#include<libintl.h>
#include<locale.h>
#include<stdio.h>
#define _(String) gettext (String)
#define _t(String1,String2,n) ngettext (String1,String2,n)
int main()
{
int i;
setlocale(LC_ALL,"");
bindtextdomain("helloworldintl","/usr/share/locale");
textdomain("helloworldintl");
printf(_("again"));
printf("\n");
printf(_("Hello World"));
printf(_("These text demonstrate that translation using po files is easier\n"));
scanf("%d",&i);
printf(_t("This number %d is of singular form","This number %d is of plural form",i),i);
printf(_("The magic number is %d\n"),i);
printf(_("These are additional words"));
printf(_("I love translation\n"));
}//main
Step 1:
執行如下指令提取程式中的字元串:
xgettext -d helloworldintl -o helloworldintl.pot --keyword=_t:1,2 -k_ -s helloworldintl.c
注意-k參數後面有個下劃線,表示需要提取以下劃線引用gettext函數的相關字元串。我弄了好幾次才弄對的!
Step 2:
然後随便用Linux上的支援Unicode的文本編輯器,比如gedit打開helloworldintl.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.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Brant I18N Hello World 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2009-12-16 17:15+0800\n"
"PO-Revision-Date: 2009-12-16 17:15+0800\n"
"Last-Translator: BrantC <[email protected]>\n"
"Language-Team: BrantC <[email protected]>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=n != 11;\n"
#: helloworldintl.c:17
#, c-format
msgid "Hello World"
#: helloworldintl.c:26
msgid "I love translation\n"
msgstr "\n"
#: helloworldintl.c:23
msgid "The magic number is %d\n"
msgstr " %d\n"
#: helloworldintl.c:24
msgid "These are additional words"
#: helloworldintl.c:19
msgid "These text demonstrate that translation using po files is easier\n"
msgstr "po\n"
#: helloworldintl.c:21
msgid "This number %d is of singular form"
msgid_plural "This number %d is of plural form"
msgstr[0] " %d "
msgstr[1] " %d "
#: helloworldintl.c:14
msgid "again"
Step 3:
把這個pot檔案copy為po檔案,即helloworldintl.po檔案,這種po檔案時要給LS team的,他們就把字元串翻譯更新到po檔案中,翻譯後的po檔案,如下:
msgstr "你好,世界"
msgstr "我愛翻譯\n"
msgstr "這個神齊的數字是 %d\n"
msgstr "這些是附加的單詞"
msgstr "這些示例文本通過po檔案翻譯更容易\n"
msgstr[0] "這個數字 %d 是單數形式"
msgstr[1] "這個數字 %d 是複數形式"
msgstr "重試"
Step 4:
然後,執行下面的指令生成mo檔案:
msgfmt helloworldintl.po -o helloworldintl.m
Step 5:
然後把mo檔案copy到相應的locale目錄下面,我這裡是/usr/share/locale/zh_CN.GB2312/LC_MESSAGES/.
Step 6:
現在可以算大功告成,執行中文版的helloworldintl:
執行英文版的helloworldintl:
哈哈,完美:)
本文轉自 xkdcc 51CTO部落格,原文連結:http://blog.51cto.com/brantc/244767,如需轉載請自行聯系原作者