格式化字符串前的`_`有何作用?xargs源码相关技术问询
_ Before the Format String in That fprintf Call? Nice catch! That little underscore is far from a typo—it’s a standard tool for making programs translatable to other languages (internationalization, or i18n for short), especially in GNU projects like xargs.
Let’s start with the code snippet you pointed out:
fprintf(stderr, _("Your environment variables take up %lu bytes\n"), (unsigned long)bc_size_of_environment());
What _() Actually Does
That _() is a macro, usually mapped to the gettext() function from the GNU gettext framework. Here’s the breakdown:
- When you wrap a string literal in
_(), you’re marking it as a candidate for translation. Tools likexgettextwill scan the entire codebase for all_("string")instances, pull them out into translation files (.pofiles), and let translators provide versions in Spanish, French, Mandarin, etc. - At runtime, if the user’s system is set to a non-default locale, the macro swaps the original string with the translated version. If no translation exists for that locale, it just uses the original string you see in the code.
Why This Matters for GNU Tools
GNU utilities like xargs are used all over the world, so supporting multiple languages is a big priority. Using _() keeps the code clean—developers write strings in their native language (usually English), and translators handle localization without touching the program’s core logic.
You’ll almost always see this paired with includes like <libintl.h> in the source code, where the macro is defined something like:
#define _(str) gettext(str)
A Quick Example
If a user has their system locale set to German, the translated string might be "Ihre Umgebungsvariablen belegen %lu Bytes\n". When xargs runs, _("Your environment variables take up %lu bytes\n") would return that German string, so the error message shows up in the user’s preferred language.
内容的提问来源于stack exchange,提问作者jaggi

