Multiple definitions gives no errors or warnings in either gcc or clang

Viewed 140

If I did

#include <stdio.h>
int a; //definition
int a; //definition
int a; //definition
int a; //definition
int a; //definition
int main() {
    return 0;
}

For example, I would get no errors or warnings from either gcc or clang despite defining a variable multiple times. Why? I thought I was allowed to declare a variable as many times as I wanted to, but could only define it once?

1 Answers

This is a tentative definition. That is each declaration of a file scope variable without an initializer is considered as a declaration not as a definition. The definition is implicitly generated at the end of the translation unit with an initializer equal to 0.

From the C Standard (6.9.2 External object definitions)

2 A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

Related