Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, why don't I get an error when I declare an global variable in different data type in an other file?

Tags:

c

extern

I have tried the following code:

File1.c:

int x;

File2.c:

extern char x;
main()
{
    x=10;
    ....
    ....
}

and compiled as

$gcc File1.c File2.c

and I didn't get any error but I was expecting one.

like image 635
Adi Avatar asked Mar 22 '13 09:03

Adi


People also ask

Can global variables be used in different files?

Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error. Static — use the static keyword to make a global variable visible only to functions within the same source file whenever possible.

Can global variables be declared anywhere in C?

An introduction to C Global Variablesj is not available anywhere outside the main function. A global variable can be accessed by any function in the program. Access is not limited to reading the value: the variable can be updated by any function.

How do you declare a global variable in C?

Use of the Global Variable in CThe global variables get defined outside any function- usually at the very top of a program. After this, the variables hold their actual values throughout the lifetime of that program, and one can access them inside any function that gets defined for that program.

Can you declare a global variable in a function C?

The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.


1 Answers

In File.c, you promise to the compiler that x is of type char. Since every translation unit is compiled separately, the compiler has no way of verifying this, and takes your word for it. And the linker doesn't do any type checking. You end up with an invalid program that builds with no errors.

This is why you should use header files. If File1.c and File2.c both got an extern declaration of x from the same header, then you would get an error when compiling File1.c (because the definition doesn't match the declaration). [Hat tip @SteveJessop]

like image 125
NPE Avatar answered Oct 26 '22 14:10

NPE