1

I have an hpp file with following code:

const float PixelsPerMeter = ConfigManager->Get<float>("koef", 100.0f);

inline const float Meters2Pixels(float meters) { return meters * PixelsPerMeter; }
inline const float Pixels2Meters(float pixels) { return pixels / PixelsPerMeter; }

const float ScreenArea = Pixels2Meters(ScreenSizeX) * Pixels2Meters(ScreenSizeY);

It worked before, but now ScreenArea = inf somehow. I use it from static function. I put a breakpoint in that function and print out the value of PixelsPerMeter(100.0), ScreenSizeX and ScreenSizeY. Everything is okay, but ScreenArea is calculated wrong.

When I write directly Pixels2Meters(ScreenSizeX) * Pixels2Meters(ScreenSizeY) instead of using ScreenArea constant everything works.

How it could be?

Roman Byshko
  • 8,591
  • 7
  • 35
  • 57
Max Frai
  • 61,946
  • 78
  • 197
  • 306

2 Answers2

2

I think, the problem is with your global variable, to be precise with its initialization.

If by the time the variable has not been dynamically initialized when you call Pixels2Meters(), the variable PixelsPerMeter is statically initialized to zero, so the function Pixels2Meters() returns inf which very much implies PixelsPerMeter is zero.

But you put break points, the story could be slightly different; it is analogous to Heisenberg uncertainty principle, in the sense that when you want to see the value of PixelsPerMeter by putting breakpoints, it shows you different value than the value when there is no breakpoints.

Also note that since the variable is declared const, without extern keyword, the variable has internal linkage, which means you will have different copy of this variable in each translation unit, in case if it declared in a header file which you include in several source files. The variable's behavior is as if it is declared static.

Another important point to be noted is that this variable is initialized twice: the first initialization is called static initialization which happens at compile-time, and second initialization is called dynamic initialization which happens at runtime. In case of static initialization, the variable is initialized to zero, and that is the value which is being used which is causing the problem. To know more about it, read this:

You should also read about this:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

When the static function is initialised is a bit complicated and may depend on system/compiler.

You probably have an issue that the ConfigManager() isn't initialised before the static function you are using it in.

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
  • As you understand, the second argument of `Get` from config is a default value in some extra cases. I tested it out (set not 100, but another value), and it's equal to 100 anyway, so, config manager works well there. – Max Frai Dec 05 '11 at 04:51