Different compilation results not using extern in C vs in C++

前端 未结 2 685
闹比i
闹比i 2021-01-11 17:07

When I declare a global variable in two different source files and only define it in one of the source files, I get different results compiling for C++ than for C. See the f

2条回答
  •  盖世英雄少女心
    2021-01-11 17:48

    I believe you are observing an extension to C known as "common symbols", implemented by most, but not all, Unix-lineage C compilers, originally (IIUC) for compatibility with FORTRAN. The extension generalizes the "tentative definitions" rule described in StoryTeller's answer to multiple translation units. All external object definitions with the same name and no initializer,

    int foo; // at file scope
    

    are collapsed into one, even if they appear in more than one TU, and if there exists an external definition with an initializer for that name,

    int foo = 1; // different TU, also file scope
    

    then all of the external definitions with no initializers are treated as external declarations. C++ compilers do not implement this extension, because (oversimplifying) nobody wanted to figure out what it should do in the presence of templates. For GCC and Clang, you can disable the extension with -fno-common, but other Unix C compilers may not have any way to turn it off.

提交回复
热议问题