Global variables and scope - C++

前端 未结 4 527
北荒
北荒 2021-01-01 02:57

I am having small problem in making a global variable works. I am using Visual Studio 2008 and standard C++.

I have two projects, one is a static library and second

4条回答
  •  北海茫月
    2021-01-01 03:35

    The problem is likely to be one of initialization order. When the program is linked, there are 2 places where globalWord is used in initialization:

    1. in the initialization of text ("string text = globalWord;")
    2. the initialization of globalWord itself

    Unfortunately, the C++ standard does not specify the order of initialization of globals that come from different modules. Something similar to Matt's answer of using a function or a simple class (a singleton, for example) to access the global value is the usual way of enforcing a particular initialization order.

    The C++ FAQ talks about this a little - if you plan to modify globalWord in your program, the situation is made a little more complex than they discuss because they don't seem to address setting the value hidden behind the "construct on first use" function. Typically something like that would require something like a singleton class.

提交回复
热议问题