1

Is it possible for clang to give a compiler error if you accidentally set a const global variable to another static const variable in C++ (in different translation units).

Since the behaviour is pretty much undefined, it would be very useful to detect if doing this accidentally.

EDIT: My question is different from the one linked above, since I'm looking for a compiler warning/error message to force me NOT to assign any static global variable to another static variable. I basically want to be forced by the compiler to avoid the whole fiasco. I'm wondering if that's possible.

user207421
  • 305,947
  • 44
  • 307
  • 483
keyboard
  • 2,137
  • 1
  • 20
  • 32
  • 1
    The point of having a global variable is to use/set it across differential translation units, unless if I am misunderstood your question. But if you want to not set anywhere else, you can make it const. – Mahesh Mar 05 '18 at 01:18
  • I edited the question sorry. I meant const variables. – keyboard Mar 05 '18 at 01:44
  • 1
    Read this: How do I prevent the “static initialization order fiasco”? https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use – Henri Menke Mar 05 '18 at 01:53
  • Possible duplicate of [Prevent static initialization order "fiasco", C++](https://stackoverflow.com/questions/29822181/prevent-static-initialization-order-fiasco-c) – Henri Menke Mar 05 '18 at 01:56
  • Thanks, defining via a function sounds nice - albeit not very ideal. We're using like 1000 string constants that need to be initialized statically. – keyboard Mar 05 '18 at 02:01

1 Answers1

0

I don't think you can throw an error automatically. I've had issues like that, and here's what I've done to fix them. You can add some global bool globalStaticsDone variable that's set to false at compile time, and on entry to main you need to set that variable to true.

Then, if you have some code anywhere that you suspect gets called from global ctors you spice it up with assert(globalStaticsDone) (or c++ throws if you prefer) to catch unexpected uses of of these objects. Then, you go and fix these uses.

In general, in complex projects that's a common problem, where some non-trivial objects are created as global statics and end up using some other globals that might not have been initialized yet. Problem gets worse if your project is cross platform and order of compilation and linking is different on your target platforms. For example on ios and android builds might have these differences: in such cases it might be undefined behavior on one build and ok on another leading to some mysterious errors.

As an alternative, some compilers might offer uninitialized read checks in debug builds.

Pavel P
  • 15,789
  • 11
  • 79
  • 128
  • Thank you, it's mostly not that I create complex objects - but that somebody accidentally assigns a static global variable to another one. That would need to be checked ;) – keyboard Mar 05 '18 at 01:43