GCC warning or error declaring a global variable multiple times

Assume the following code:

ac:

#include <stdio.h>

int a;
int func();

int main(int argc, char **argv) {
a = 7;
int a2 = func();
printf("a is %d, a2 is %d\n", a, a2);
return 0;
}

and bc:

int a;

int func()
{
a = 9;
return a;
}

When compiling with g++ a.c b.c -Wall -O0it, it creates a binding error, as expected. However, when called, gcc a.c b.c -Wall -O0it does not cause any warnings and errors!

Conclusion by the a is 9, a2 is 9way.

gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1 ~ 16.04.4)

Why does the GCC allow this? I was surprised by this behavior. If you initialize the variables upon declaration, then the connection to GCC will also fail.

+4
source share
1 answer

g++ a.c b.c -Wall -O0 , . gcc a.c b.c -Wall -O0 !

a ( ), C. , b.c - a . , a.c b.c , , ( , , ). undefined:

C11, 6.9/5:

- , ( ) . , , ( sizeof _Alignof, ), - ; .161

gcc. , gcc, C-. (), C.

g++, ++, , ++ . ++. , g++ . . ++.

+5

Source: https://habr.com/ru/post/1669881/


All Articles