Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is accessing a static struct::var without an object undefined behaviour? [duplicate]

Tags:

c++

According to Compiler Explorer, only some will build this code:

struct s { static int i; };

int main( int argc, char *argv[] )
{
  s::i = 1;
  return 0;
}

Most newer C++ compilers fail at linking.

  • GCC 4.7.2 works, 4.7.3 and newer fail
  • Clang 3.2 works, 3.4 and newer fail
  • msvc works with all versions

So, is this undefined behaviour or should this work?

like image 269
dee Avatar asked Jan 25 '23 18:01

dee


1 Answers

This code violates the One Definition Rule (ODR), which requires a single definition of every entity that is used in the program.

There is no definition of s::i in the program, but you are using it, and so the code violates the ODR. Any violation of the ODR makes the code ill-formed, no diagnostic required. This means the compiler can do anything it wants, including rejecting the code, or compiling it and producing an executable program (which could do anything it wants).

like image 57
cigien Avatar answered Jan 30 '23 00:01

cigien