Skip to content

Using The Gettext Library In Standard Cpp Projects

laurent22 edited this page Mar 28, 2013 · 1 revision

Introduction

The library is generic enough to be used with any C++ project. Except for it's Qt wrapper, it's not tied to any particular framework and makes use of the standard C++ library.

Details

Setting up the library

In order to initialize the catalogue manager, the locale, catalogue name and directory must be provided. For instance, if we want to set the locale to traditional Chinese, and if the catalogues are named "catalogue.mo" and located in Data/Locales, we would use the following code:

#include <LauGettext.h>

LauGettext::instance()->setLocale("cn_TW"); // Set the locale
LauGettext::instance()->setCatalogueName("catalogue"); // Set the name of the mo files
LauGettext::instance()->setCatalogueLocation("Data/Locales"); // Set the catalogue folder

QtGettext is now set to use the file in Data/Locales/cn_TW/catalogue.mo.

Also note that if this file is not available, QtGettext will try to load Data/Locales/cn/catalogue.mo (if available) as an alternative.

Retrieving the translation of a string

To get the translation of a string, use the following code:

#include <LauGettext.h>

char* someString = "Some string to be translated\0";
GettextMessage* message = LauGettext::instance()->getTranslation(someString, strlen(someString));
if (!message) {
   std::cout << "The string doesn't have a translation."
} else {
   std::count << "Translation = " << message->string << std::endl;
   std::count << "Length= " << message->length << std::endl;
}

Obviously, since the code above is rather verbose it's recommended to wrap it in a function and an wrap translatable strings in that function. See QtGettext.cpp to see how it can be done.