What is the visibility / scope of a global variable in C?

I have two .c files: A1.c and A2.c

A1.c as follows:

int i=0; void main() {} 

A2.c as follows:

 int i=0; void func() {} 

It compiles well, but when I try to link the two .o files, a "multiple definition i" error occurs. I understand that i is a global variable, but you do not need to use the extern keyword for use in other files. And in my project I do not use extern . So why am I getting an error message?

+4
source share
4 answers

At compile time, the compiler exports each global character to assembler as strong or weak, and assembler implicitly encodes this information in the character table of the moved object file. Functions and initialized global variables receive strong characters. Uninitialized global variables receive weak characters.

Given this concept of strong and weak characters, Unix-linkers use the following rules for working with repeatedly defined characters:

Rule 1: Several strong characters are not allowed.
Rule 2:. If you have a strong character and several weak characters, select a strong character.
Rule 3: If there are several weak characters, select any of the weak characters.

Your code, A1.c as follows:

 int i=0; // Strong Symbol void main() {} 

A2.c as follows:

 int i=0; // Strong symbol void func() {} 

In accordance with Rule 1, this is not permitted.

For more information: http://www.geeksforgeeks.org/how-linkers-resolve-multiply-defined-global-symbols/

+5
source

In short, a statement like

 extern int i; 

is an ad, and a statement

 int i=0; 

- definition.

In C, you can repeatedly declare a variable in a program, but you can define it only once. The first statement means A2 that the definition of the variable i is in another file. For one, I cannot understand why you are so afraid of using "extern".

+5
source

In C, a global variable can be accessed from another compilation unit while this other compilation unit sees that it exists by declaring it extern . The compiler does the task of linking the extern declaration and the definition in another .c.

If you want it to be visible only to the .c you are compiling, you must specify it as static

 static int i = 0; 
+3
source

Of course, it doesn’t work by reference: it tries to merge two object files that reference the object in two different memory cells.

In such cases, the actual definition of your variable should be UNIQUE in the entire source code, and all other references to this variable should be made using the external keyword (as you sat).

Compilation does not whine, because it does not know the relationship of your two files, only the linker should understand this.

0
source

All Articles