首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

gettext 實作軟體本地化 (L10N) 完整範例教學

     編輯:關於C語言

本文整理自《Free/Open Source Software Guide to Localization》第 10 章範例,在 Red Hat 5.3 環境實測通過,示範 gettext 核心工作流:標記字串 → 提取模板 → 翻譯編輯 → 編譯二進位 → 部署測試。

原始碼: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\n"));
    printf(_("Hello World\n"));
    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"));
    return 0;
}
  • setlocale(LC_ALL, ""):依環境變數設定當前地區
  • bindtextdomain:指定翻譯檔搜尋根目錄
  • textdomain:設定當前應用程式網域
  • _() 對應 gettext (單數),_t() 對應 ngettext (複數判斷)

四步驟建立翻譯檔

  1. 提取字串產生 .pot 模板:
    xgettext -d helloworldintl -o helloworldintl.pot \
      --keyword=_t:1,2 -k_ -s helloworldintl.c

    -k_ 指定底線巨集,--keyword=_t:1,2 處理雙參數複數形式。

  2. 複製 .pot 為 .po 並翻譯:編輯 msgstr 欄位填入目標語言 (範例為繁體中文),複數形式填寫 msgstr[0]、msgstr[1]。
  3. 編譯 .po 為 .mo 二進位檔:
    msgfmt helloworldintl.po -o helloworldintl.mo
  4. 部署至地區目錄:
    cp helloworldintl.mo /usr/share/locale/zh_TW/LC_MESSAGES/

    目錄結構需符合 /usr/share/locale/<語言代碼>/LC_MESSAGES/。

執行驗證

設定 LANG=zh_TW 執行即顯示中文介面;LANG=C 則回退英文原文。gettext 機制完全在執行期動態載入 .mo,無需重新編譯主程式,極適合開源專案多語言維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved