You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

设置fr_FR.UTF-8本地化后为何显示德语翻译结果?

德语本地化正常但法语NLS本地化失效排查

问题背景

刚接触NLS,完成德语(母语)本地化后尝试法语本地化,初始失败。使用locale-gen安装fr_FR后,setlocale()可识别fr_FR.UTF-8,但程序输出仍为德语。

代码片段

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

#define _(String)   gettext(String)

#define PACKAGE     "nls-test"
#define LOCALEDIR   "/usr/share/locale/"

int main(int argc, char *argv[])
{
printf("LOCALE = %s\n",argv[1]);
setlocale(LC_ALL, argv[1]);
printf("check=%s\n",setlocale(LC_ALL, NULL));

bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);

printf(_("Hello World\n"));
printf(_("My computer has hung up. My laundry never does that\n"));
}

MO文件信息

  • 德语MO路径:/usr/share/locale/de_DE/LC_MESSAGES/nls-test.mo(正常工作)
  • 法语MO路径:/usr/share/locale/fr_FR/LC_MESSAGES/nls-test.mo(失效)

法语MO文件的strings输出:

$ strings /usr/share/locale/fr_FR/LC_MESSAGES/nls-test.mo

Hello World
My computer has hung up. My laundry never does that
Project-Id-Version: PACKAGE VERSION
Report-Msgid-Bugs-To: 
PO-Revision-Date: 2022-08-08 16:55+0200
Last-Translator: Michael Adam <michael.adam@abk-technology.de>
Language-Team: French
Language: fr
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Plural-Forms: nplurals=2; plural=(n > 1);
bonjour le monde
Mon ordinateur a raccroch
. Mon linge ne fait jamais 

错误原因排查

  • msgid匹配不严格:代码中_("Hello World\n")和_("My computer has hung up. My laundry never does that\n")的msgid包含换行符\n,但法语MO文件中的msgid却没有换行符,gettext无法匹配到对应翻译,会 fallback 到系统默认locale(德语)输出。
  • 法语翻译内容不完整:第二句翻译被拆分为两行且未完成(Mon ordinateur a raccroch和. Mon linge ne fait jamais ),既无法完整匹配原句,也无法输出正确翻译。
  • MO文件完整性存疑:翻译内容的截断说明MO文件生成过程可能存在错误,比如PO文件未正确编辑就生成MO。

修复步骤

  1. 修正PO文件的msgid:确保PO文件中的msgid与代码中完全一致(包括换行符),例如:
    msgid "Hello World\n"
    msgstr "bonjour le monde\n"
    
    msgid "My computer has hung up. My laundry never does that\n"
    msgstr "Mon ordinateur a planté. Mon linge ne fait jamais ça\n"
    
  2. 修复翻译内容:将截断的法语翻译补全为完整句子,修正拼写错误(如raccroch应为planté或raccroché)。
  3. 重新生成MO文件:使用msgfmt工具从修正后的PO文件生成MO:
    msgfmt -o nls-test.mo nls-test.po
    
  4. 替换并验证MO文件权限:将新生成的MO文件放到/usr/share/locale/fr_FR/LC_MESSAGES/下,确保权限为所有用户可读:
    sudo cp nls-test.mo /usr/share/locale/fr_FR/LC_MESSAGES/
    sudo chmod 644 /usr/share/locale/fr_FR/LC_MESSAGES/nls-test.mo
    
  5. 明确指定消息区域:运行程序时可单独指定LC_MESSAGES,或在代码中单独设置:
    // 替换原setlocale行,或额外添加
    setlocale(LC_MESSAGES, argv[1]);
    

内容的提问来源于stack exchange,提问作者madam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:03:22