How to define extern variable along with declaration?

橙三吉。 提交于 2019-12-03 23:57:05

All three versions of the standard — ISO/IEC 9899:1990, ISO/IEC 9899:1999 and ISO/IEC 9899:2011 — contain an example in the section with the title External object definitions (§6.7.2 of C90, and §6.9.2 of C99 and C11) which shows:

EXAMPLE 1

int i1 = 1;        // definition, external linkage
static int i2 = 2; // definition, internal linkage
extern int i3 = 3; // definition, external linkage
int i4;            // tentative definition, external linkage
static int i5;     // tentative definition, internal linkage

The example continues, but the extern int i3 = 3; line clearly shows that the standard indicates that it should be allowed. Note, however, that examples in the standard are technically not 'normative' (see the foreword in the standard); they are not a definitive statement of what is and is not allowed.

That said, most people most of the time do not use extern and an initializer.

ouah

This code is perfectly valid.

But any compiler is free to issue additional (informative or not) diagnostics:

(C99, 5.1.1.3p1 fn 8) "Of course, an implementation is free to produce any number of diagnostics as long as a valid program is still correctly translated."

What a compiler cannot do is not emitting a diagnostic when there is a constraint or syntax violation.

EDIT:

As devnull put in the OP question comments, Joseph Myers from gcc team explains in a bug report questioning this diagnostic:

"This is a coding style warning - the code is valid, but extremely unidiomatic for C since "extern" is generally expected to mean that the declaration is not providing a definition of the object."

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