c & c++ default global variable linkage, multiple declaration & definition problem

空扰寡人 提交于 2019-11-28 21:10:19
CB Bailey

It's not strictly legal. int a; is a tentative definition in C. You are allowed multiple tentative definitions and at most one non-tentative definition per translation unit of each object with external linkage in C, but only one definition across all translation units in a program.

It is a commonly implemented extension to allow tentative definitions across multiple translation units in C so long as not more than one translation unit contains a non-tentative definition, but it's not strictly standard.

In C++ int a; is just a definition - there's no concept of tentative - and it's still illegal to have multiple definitions of an object across the translation units of a program.

For the C case, you may wish to look at this question.

Artefacto

It's illegal in both, but C compilers generally implement an extension. See this answer.

There are three ways for resolution of problem:

  1. If variable a is the same in both files, you must declare it as extern in all files except one. extern keyword says to linker that this name is located in another files.

  2. You may use static keyword to limit scope of variable to one file. In which it is declared.

  3. Or you may use nameless namespace.

g++ compiler is more strict then gcc compiler. It also depends on version of gcc, may be higher version of gcc i.e. 4.X onwards it can give same error.

Use extern to avoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!