“multiple definition of value” when compiling C program with uninitialized global in g++ but not gcc

前端 未结 2 1945
粉色の甜心
粉色の甜心 2021-01-06 07:16

I\'m trying to understand the usage of extern and global variable declaration in header files so I came up with the following test program written in C.

The main.c f

相关标签:
2条回答
  • 2021-01-06 07:32

    C and C++ are different languages. Case in point, the above program is a valid C program but in ill-formed C++ program. You have violated C++'s one definition rule. There is no corresponding rule in C.

    When compiling with gcc, you are compiling the above text as a C program. When compiling with g++, you are compiling the above text as a C++ program.

    0 讨论(0)
  • 2021-01-06 07:51

    When compiled with gcc, uninitialized global variable (such as nValue) will be treated as a common symbol. The same common symbol occurred in different compilation unit will be merged during link time. If compiled with g++ (which means that the source program will be treated as C++ program), uninitialized global variable are implicitly initialized with a default value 0. Since global.h is included in multiple source files, the compiler will consider the symbol nValue defined multiple times.

    Please also have a look at this post: Why uninitialized global variable is weak symbol?

    0 讨论(0)
提交回复
热议问题