Skip to content
Advertisement

How is the locale of a C program set to the “C” locale?

A C program inherits its locale environment variables when it starts up. This happens automatically. However, these variables do not automatically control the locale used by the library functions, because ANSI C says that all programs start by default in the standard "C" locale.

I have read that a C program must have the C locale when started, so the C program must do something like this when started:

setlocale(LC_ALL, "C");

But how does this line of code end up in the C program? Does the compiler add it for me?

Advertisement

Answer

The compiler does not modify the source code and add an explicit call to setlocale() to your main program. Rather, the implementation (the combination of compiler and library) is required to ensure that the program behaves ‘as if’ there was a call to setlocale() at the start.

There are many other aspects of program behaviour that the implementation must ensure work correctly too. For example, it must ensure that stdin, stdout, and stderr are set up correctly — you don’t have to open those streams explicitly in the main() program because the library ensures that they are set up before main() is called. On POSIX systems, the startup code ensures that the environ global variable is set appropriately. You can see a lot of the relevant information in the POSIX specification of execve(), including:

For the new process image, the equivalent of:

setlocale(LC_ALL, "C")

shall be executed at start-up.

The C standard also says much the same thing C11 §7.11.1.1 The setlocale function says:

At program startup, the equivalent of

setlocale(LC_ALL, "C");

is executed.

The details of how any specific implementation achieves the effect are inherently implementation-specific, but it typically is achieved by initializing selected global variables with the appropriate correct values. The standard doesn’t say how the implementation must achieve the effect; it simply says that it must achieve it.

Advertisement