LoginSignup
7
6

More than 5 years have passed since last update.

C言語の helloworld を gettext で日本語化

Last updated at Posted at 2017-02-12

いいサンプルが見つからなったので。

元となる helloworld プログラム

hello0.c
#include <stdio.h>

int main()
{
    printf("hello, world\n");
}

コンパイル
 $ gcc -o hello hello0.c

動作確認

$ ./hello
hello, world

gettextに対応するとこうなる

hello1.c
#include <stdio.h>

/* setlocale() */
#include <locale.h>

/* bindtextdomain(), textdomain() */
#include <libintl.h>

int main()
{
    /* ロケール名を環境変数から取得 */
    setlocale(LC_ALL, "");

    /* ドメイン名"hello"のメッセージカタログディレクトリをカレントディレクトリに設定 */
    bindtextdomain("hello", ".");

    /* ドメイン名を"hello"に設定 */
    textdomain("hello");

    printf(gettext("hello, world\n"));
}

コンパイル
$ gcc -o hello hello1.c

動作確認(まだ日本語化されていません)

$ ./hello
hello, world

ソースファイルからpotファイル(hello.pot)作成
 $ xgettext -d hello -o hello.pot hello1.c

potファイル(hello.pot) からpoファイル(hello.po) 作成
 $ msginit --locale ja_JP.UTF-8 --input hello.pot --output-file hello.po

poファイル(hello.po)を編集(「hello, world」に対応する日本語を書き足す)
 vi hello.po

hello.po
# PACKAGE パッケージに対する英訳.
# Copyright (C) 2017 THE PACKAGE'S COPYRIGHT HOLDER
(中略)
#: hello1.c:20
#, c-format
msgid "hello, world\n"
msgstr "こんにちは、世界!\n"

poファイル(hello.po)から、moファイル(hello.mo)を作成
 $ msgfmt -o hello.mo hello.po

指定のディレクトリを作成して、moファイルを配置

$ mkdir -p ja/LC_MESSAGES
$ cp hello.mo ja/LC_MESSAGES/hello.mo

動作確認

$ ./hello
こんにちは、世界!
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6