Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to support multiple language in a Linux C/C++ program?

Tags:

c++

c

linux

locale

For example, in this simplest hello world program:

#include <iostream>
int main()
{
    std::cout<<"Hello World!"<<std::endl;
    return 0;
}

I'd like to see French if user's environment LANG is set to fr_FR, it might looks like:

$ ./a.out
Hello World!

$ LANG=fr_FR.utf8
$ ./a.out
Bonjour tout le monde!

Is there a guideline of how to archieve this in Linux?

like image 231
Deqing Avatar asked Sep 03 '25 05:09

Deqing


2 Answers

The key is to use "resources" (one per-language, configured to be read at runtime) vs. hard-coding strings. GUI frameworks like Qt and GTK+ make this (relatively) easy.

Here's a link to the Pango" library used by GTK+ (but not, emphatically, exclusive to GTK+):

  • http://www.pango.org/

Here's a tutorial on using Pango:

  • http://x11.gp2x.de/personal/google/

And here's a tutorial on "gettext()" (which, I believe, Pango uses):

  • http://inti.sourceforge.net/tutorial/libinti/internationalization.html
like image 78
paulsm4 Avatar answered Sep 04 '25 20:09

paulsm4


Two questions here.

  1. You can easily make your program internationalized/localized using the Gettext library.

  2. You can check the user's environment variables using either the standard function `getenv()’:

    const char *langcode = getenv("LANG");

or some implementations (I believe Linux and Mac OS X included) support a 3-argument main function:

int main(int argc, char **argv, char **envp)
{
    char **e;
    char *langcode;
    for (langcode = NULL, e = envp; e != NULL; e++)
    {
        if (strstr(*e, "LANG") != NULL)
        {
             langcode = strchr(*e, '=') + 1;
             break;
        }
    }

    printf("Language: %s\n", langcode);
}