Support C ++, Multilanguage / Localization

What is the best way to add multilingual support to a C ++ program?

If possible, the language should be read from a regular text file containing something like a key-value pair (§WelcomeMessage§ "Hello% s!").

I thought about adding a localizedString (key) function that returns the string of the loaded language file. Are there any better or more effective ways?

//half-pseudo code //somewhere load the language key value pairs into langfile[] string localizedString(key) { //do something else here with the string like parsing placeholders return langfile[key]; } cout << localizedString(§WelcomeMessage§); 
+7
source share
4 answers

The simplest way without external libraries:

//strings.h

 enum { LANG_EN_EN, LANG_EN_AU }; enum { STRING_HELLO, STRING_DO_SOMETHING, STRING_GOODBYE }; 

//strings.c

 char* en_gb[] = {"Well, Hello","Please do something","Goodbye"}; char* en_au[] = {"Morning, Cobber","do somin'","See Ya"}; char** languages[MAX_LANGUAGES] = {en_gb,en_au}; 

This will give you what you want. Obviously, you could read the lines from the file. I.e.

//en_au.lang

 STRING_HELLO,"Morning, CObber" STRING_DO_SOMETHING,"do somin'" STRING_GOODBYE,"See Ya" 

But you will need a list of line names to match the line names. i.e.

//parse_strings.c

 struct PARSE_STRINGS { char* string_name; int string_id; } PARSE_STRINGS[] = {{"STRING_HELLO",STRING_HELLO}, {"STRING_DO_SOMETHING",STRING_DO_SOMETHING}, {"STRING_GOODBYE",STRING_GOODBYE}}; 

The above should be a little easier in C ++, since you could use the enum classes for the toString () method (or whatever it may be - can't be bothered with finding it).

All you have to do is analyze the language files.

Hope this helps.

PS: and to access the lines:

 languages[current_language][STRING_HELLO] 

PPS: apologies for half the answer C ++ C ++.

+10
source

The ICU library is designed for just that.

+6
source

Space_C0wb0w's suggestion is a good one. We are currently successfully using the ICU for this in our products.

Repeating his comment on his answer: it is really difficult to say that the ICU is "small, clean, uncomplicated." The ICU has “random” complexity emanating from its Java-ish interface, but most of the complexity and size simply comes from the complexity and size of the problem domain it is accessing.

If you don’t need the full power of the ICU and are only interested in “message translation”, you can see the GNU gettext , which, depending on your platform and licensing requirements, can be a “smaller, cleaner, and less complicated” alternative.

The Boost.Locale project is also an interesting alternative. In fact, its functionality Message formatting is based on the gettext model.

+5
source

Since you are asking for a better way (and not mentioning the platform), I would recommend GNU Gettext .

Perhaps this is the most comprehensive and mature internationalization library for C / C ++ programming.

+3
source

All Articles