3.6.3.3 Common Option
The -fcommon
option tells the compiler to allow merging of tentative definitions by the linker. This is the default action if no option is specified.
The definition for a file-scope object without a storage class specifier or initializer is known as a tentative definition in the C standard. Such definitions are treated as external references when the -fcommon
option is specified and will be placed in a common block. As such, if another compilation unit has a full definition for an object with the same name, the definitions are merged and storage allocated. If no full definition can be found, the linker will allocate unique memory for the object tentatively defined. Tentative definitions are thus distinct from declarations of a variable with the extern
keyword, which never allocate storage.
In the following code example:
extra.c
int a = 42; /* full definition */
main.c
int a; /* tentative definition */
int main(void) {
...
}
The object a
is defined in extra.c and tentatively defined in main.c. Such code will build when using the -fcommon
option, since the linker will resolve the tentative definition for a
with the full definition in extra.c.
The -fno-common
form of this option inhibits the merging of tentative definitions by the linker, treating tentative definitions as a full definition if the end of the translation unit is reached and no definition has appeared with an initializer. Building the above code, for example, would result in a multiple definition of 'a'
error, since the tentative definition and initialized definition would both attempt to allocate storage for the same object. If you are using this form of the option, the definition of a
in main.c should be written extern int a;
to allow the program to build.