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

前端 未结 2 1947
粉色の甜心
粉色の甜心 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: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?

提交回复
热议问题