Why doesn't this “undefined extern variable” result in a linker error in C++17?

前端 未结 4 1008
后悔当初
后悔当初 2021-02-05 00:43

I have compiled and ran the following program in a C++17 compiler (Coliru). In the program, I declared an extern variable, but did not defi

4条回答
  •  清歌不尽
    2021-02-05 01:49

    In your case the variable is used in discarded statements only. However, even if we ignore that fact, C++ language specification still explicitly states that no diagnostic is required for missing definitions

    3.2 One-definition rule

    4 Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement (6.4.1); no diagnostic required.

    The language specification understands that an optimizing compiler might be smart enough to eliminate all odr-uses of a variable. In that case it would be excessive and unnecessary to require the implementation to detect and report the potential ODR violations.

提交回复
热议问题