Wednesday, February 3, 2016

How to use gettext

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

#define _(String) gettext (String)

int main()
{
    setlocale(LC_MESSAGES, "ru_RU.UTF-8");
    setlocale(LC_CTYPE, "ru_RU.UTF-8");
    bindtextdomain("helloworld","dir");
    textdomain("helloworld");
    printf(_("Hello World\n"));
    return 0;
}

$ xgettext -d helloworld -o helloworld.po -k_ -s helloworld.c

Now edit .po file (set UTF-8 and translation):

-"Content-Type: text/plain; charset=CHARSET\n"
+"Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 
 #: /tex_tmp/test.w:14
 msgid "Hello World\n"
-msgstr ""
+msgstr "привет\n"

$ msgfmt helloworld.po -o helloworld.mo

In the end you must get the following picture:

$ ls -l
total 24
-rwxr-xr-x 1 user user 7184 Feb  3 15:45 helloworld
-rw-r--r-- 1 user user  277 Feb  3 16:14 helloworld.c
-rw-r--r-- 1 user user  439 Feb  3 15:44 helloworld.mo
-rw-r--r-- 1 user user  668 Feb  3 15:43 helloworld.po
lrwxrwxrwx 1 user user    1 Feb  3 16:16 LC_MESSAGES -> .
lrwxrwxrwx 1 user user    1 Feb  3 16:17 ru -> .

now type `pwd' and put the result to "bindtextdomain" in program source.

now compile the program and run with `./helloworld'