Search code examples
c++linker-errorsexternc++17if-constexpr

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


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 define it. However, the compiler doesn't give a linker error.

#include <iostream>

extern int i; // Only declaration

int func() 
{
    if constexpr (true)
        return 0;
    else if (i)
        return i;
    else
        return -1;
}

int main() 
{
    int ret = func();
    std::cout<<"Ret : "<<ret<<std::endl;
}

Why doesn't the compiler give a linker error?


Solution

  • 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.