Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 程式國際化 (i18n) 完整實作指南:從 gettext 到多語系部署

編輯:Linux 教學

國際化 (i18n) 核心概念

國際化是指軟體在設計架構上支援多語言擴展特性,功能與代碼設計不針對特定語言或地區。核心工具鏈為 GNU gettext 工具組。

完整實作九步驟

1. 編輯原始程式

需包含標準頭文件,主函數呼叫關鍵函數:

#include <stdio.h>
#include <locale.h>
#include <libintl.h>
#include <stdlib.h>

#define _(String) gettext(String)

int main(int argc, char **argv) {
    setlocale(LC_ALL, "");
    bindtextdomain("gettext", ".");
    textdomain("gettext");
    printf("%s\n", _("one world, one dream!"));
    return 0;
}

2. 編譯原始程式

gcc -o gettext gettext.c

3. 建立翻譯模板 (.pot)

xgettext --keyword=_ gettext.c -o gettext.pot

4. 產生可攜式物件 (.po)

cp gettext.pot gettext.po

每種語言對應一個 .po 檔案,包含 msgid (原文) 和 msgstr (譯文) 配對。

5. 編輯翻譯內容與編碼

gedit gettext.po  # 或 vim

關鍵:必須將 charset 設為 UTF-8,否則會出現編碼警告。

6. 編譯二進制物件 (.mo)

msgfmt gettext.po -o gettext.mo

7. 部署 .mo 到正確目錄結構

預設目錄:/usr/share/locale。範例中因 setlocale() 設定當前目錄,需建立:

mkdir -p zh_CN/LC_MESSAGES en_US/LC_MESSAGES
cp gettext.mo zh_CN/LC_MESSAGES/
cp gettext_en.mo en_US/LC_MESSAGES/

8. 設定環境變數

export LANG=zh_CN.UTF-8
# 或
export LANG=en_US.UTF-8

9. 執行驗證

./gettext

國際化程式升級流程

當原始碼修改後,如何保留既有翻譯並同步新增內容?

  1. 修改原始程式
  2. 重新執行 xgettext 產生新 .pot
  3. 備份舊 .po:mv gettext.po old_gettext.po
  4. 合併新舊:msgmerge old_gettext.po gettext.pot --output-file gettext.po
  5. 記錄差異:diff -u old_gettext.po gettext.po > old_gettext.diff
  6. 清理舊檔:rm -f old_gettext.po
  7. 重新編譯 .mo、部署、設定環境、執行驗證

常見坑點與解決方案

問題原因解決
翻譯不生效setlocale() 與 .mo 目錄結構不一致確保 setlocale(LC_ALL, "") 與目錄結構一致
編碼警告.po 中 charset 非 UTF-8編輯 .po 將 charset 改為 UTF-8
多語言切換失效環境變數切換但 .mo 未對應部署每種語言獨立 .po/.mo 部署到對應目錄
修改不生效舊執行檔殘留重新編譯前刪除舊執行檔

核心函數解析

  • setlocale(LC_ALL, ""):依環境變數設定當前地區
  • bindtextdomain("domain", "/path"):綁定翻譯域與路徑
  • textdomain("domain"):設定當前翻譯域
  • gettext("string"):查詢翻譯,未找到回傳原文
  • _() 巨集:簡化 gettext() 呼叫,兼容 xgettext 提取
Copyright © Windows教程網 All Rights Reserved