How do I prevent my 'unused' global variables being compiled out?

前端 未结 9 1170
攒了一身酷
攒了一身酷 2020-12-10 00:42

I\'m using static initialisation to ease the process of registering some classes with a factory in C++. Unfortunately, I think the compiler is optimising out the \'unused\'

相关标签:
9条回答
  • 2020-12-10 01:15

    How about using the keyword volatile? It will prevent the compiler from too much optimization.

    0 讨论(0)
  • 2020-12-10 01:16

    you could use

    #pragma optimize off
    int globalVar
    #pragma optimize on
    

    but I dunno if that only works in Visual Studio ( http://msdn.microsoft.com/en-us/library/chh3fb0k(VS.80).aspx ).

    You could also tell the compiler to not optimize at all, especially if you're debugging...

    0 讨论(0)
  • 2020-12-10 01:23

    I have same setup & problem on VS2008. I found that if you declare you class with dllexport it will not optimize.

    class __declspec( dllexport ) Cxxx
    {
    .
    }
    

    However this generates a lot of warnings in my case because I must declare all classes used in this class also as dllexport.

    All optimizations are off (in debug mode), still this is optimized. Also volatile/pragma optimize off. On global variable created of this class (in same cpp file) etc does not work.

    Just found that dllexport does require at least to include header files of these classes in some other cpp file from exe to work! So only option is to add a file with calls to some static members for each class, and add this file to all projects used these classes.

    0 讨论(0)
  • 2020-12-10 01:24

    The compiler should never optimize away such globals - if it does that, it is simply broken.

    0 讨论(0)
  • 2020-12-10 01:24

    You can force that one object (your list of types) pulls some other objects with it by partially linking them before building the complete static lib.

    With GNU linker:

    ld -Ur -o TypeBundle.o type1.o type2.o type3.o static_list.o
    ld -static -o MyStaticLib.a type_bundle.o other_object.o another_object.o ...
    

    Thus, whenever the static list is referenced by code using the library, the complete "TypeBundle.o" object will get linked into the resulting binary, including type1.o, type2.o, and type3.o.

    While at it, do check out the meaning of "-Ur" in the manual.

    0 讨论(0)
  • 2020-12-10 01:27

    The compiler is not allowed to optimiza away global objects.
    Even if they are never used.

    Somthing else is happening in your code.
    Now if you built a static library with your global object and that global object is not referenced from the executable it will not be pulled into the executable by the linker.

    0 讨论(0)
提交回复
热议问题