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

前端 未结 4 1005
后悔当初
后悔当初 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:32

    Because the variable isn't odr-used. You have a constexpr if there that always discards the branch that could use it.

    One of the points of constexpr if is that the discarded branch need not even compile, only be well-formed. That's how we can place calls to non-existing member functions in a discarded branch.

    0 讨论(0)
  • 2021-02-05 01:38

    This has alrady been answered, but if you are interested, cppreference.com has exactly this example for constexpr if:

    Constexpr If

    The statement that begins with if constexpr is known as the constexpr if statement.

    In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool. If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.
    [...]
    The discarded statement can odr-use a variable that is not defined:

    extern int x; // no definition of x required
    int f() {
    if constexpr (true)
        return 0;
    else if (x)
        return x;
    else
        return -x;
    }
    
    0 讨论(0)
  • 2021-02-05 01:46

    Because the compiler produces compiler errors, the linker would yield linker errors ...

    No, seriously:

    if constexpr (true)
    

    is always true, so the compiler ignores the rest of the if-clause because it is never reached. So i is never used actually.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题