As expected, when the hello executable is run under the default locale
(usually the C locale) it prints ``Hello, world!'' in the terminal. Besides
some initial setup work, the only additional burden faced by the programmer is
to replace any string to be printed with gettext(string), i.e., to
instead pass the string as an argument to the gettext function. For lazy
people like myself, the amount of extra typing can be reduced even further by
a CPP macro, e.g., put this at the beginning of the source code file,
#define _(STRING) gettext(STRING)
and then use _(string) instead of gettext(string).
Let us dissect the program line-by-line.
- locale.h defines C data structures used to hold locale
information, and is needed by the setlocale function. libintl.h
prototypes the GNU text utilities functions, and is needed here by
bindtextdomain, gettext, and textdomain.
- The call to setlocale () on line 7, with LC_ALL as the first argument
and an empty string as the second one, initializes the entire current locale
of the program as per environment variables set by the user. In other words,
the program locale is initialized to match that of the user. For details see
``man setlocale.''
- The bindtextdomain function on line 8 sets the base directory for the
message catalogs for a given message domain. A message domain is a set of
translatable messages, with every software package typically having its own
domain. Here, we have used ``hello'' as the name of the message domain for
our toy program. As the second argument, /usr/share/locale, is the default
system location for message catalogs, what we are saying here is that we are
going to place the message catalog in the default system directory. Thus, we
could have dispensed with the call to bindtextdomain here, and this
function is useful only if the message catalogs are installed in a
non-standard place, e.g., a packaged software distribution might have
the catalogs under a po/ directory under its own main directory. See ``man
bindtextdomain'' for details.
- The textdomain call on line 9 sets the message domain of the current
program to ``hello,'' i.e., the name that we are using for our example
program. ``man textdomain'' will give usage details for the function.
- Finally, on line 10, we have replaced what would normally have been,
printf( "Hello, world!\n" );
with,
printf( gettext( "Hello, world!\n" ) );
(If you are unfamiliar with C, the
\n at the end of the string
produces a newline at the end of the output.) This simple modification to all
translatable strings allows the translator to work independently from the
programmer. gettextize eases the task of the programmer in adapting a
package to use GNU gettext for the first time, or to upgrade to a newer
version of gettext.
Gora Mohanty
2004-07-24