Static const item defined in another file

I am working on a static analyzer for C ++ 11. There is an interaction between the static constant members of the class and the binding, for which I am not sure if this is defined. My static analyzer should warn about this only if this construct is not defined.

Example:

in the f1.cpp file:

struct Foo { static const int x = 2; }; int main(void) { return *&Foo::x; } 

and in f2.cpp file:

 struct Foo { static int x; }; int Foo::x; 

Two files compiled and associated with clang++ -std=c++11 -Weverything f1.cpp f2.cpp do not cause a warning and create a binary file that returns 0. The same files when compiled with g++ -std=c++11 -Wall -Wextra -pedantic f1.cpp f2.cpp do not raise a warning and return 2.

My intuition is that this program is not defined, but a warning is not required because:

  • both Foo :: x names have an external connection after N3376 [basic.link] p5:

    In addition, a member function, a static data member, [...] has a typedef name for binding purposes (7.1.3), has an external link if the class name has an external link.

  • but they violate the requirement of N3376 [basic.link] p10:

    After all type settings (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations related to this variable or function should be identical [...] Violation of this rule for type identity does not require diagnostics.

To be 100% sure of this, a definition for these "all type settings" is required, but cannot be found in the C ++ 11 standard. Are there any arguments, and are these arguments correct?

+6
source share
1 answer

This is a violation of ODR. Type Foo has different declarations in each file.

One definition says that x is declared with an external connection (it can be anything, it is determined when binding), and the other is a compile-time constant with a value of 2.

+3
source

Source: https://habr.com/ru/post/1015404/


All Articles