3

For solving some exercise I need to have global objects run in a C++ code like below. But when I run it using MS VS compiler, that global variable will not be run.

    #include <iostream>
    #include <string>
    using namespace std;

    template <class T>
    class Tracer {
        string cons, dest;
    public:
        Tracer(string c, string d) : cons(c), dest(d) {
            cout << "A(n) '" << cons << "' object was created.\n";
        }

        void mem_ob() {
            Tracer<string> s("string", "string");
        }

        ~Tracer() {
            cout << "The '" << dest << "' object was destructed.\n";
        }
    };

    //----------------------------

    Tracer<double> d("double", "double");

   //------------------------------------

    int main() {
        Tracer<int> t("int", "int");
        t.mem_ob();

        system("pause");
        return 0;
    }

The d object isn't run. How to get it run please?

Franky
  • 1,181
  • 2
  • 11
  • 33
  • What version are you using (service pack) ? This works on gcc/VS2013, can't test on 2015 atm. – Floris Velleman Mar 10 '16 at 08:57
  • I'm using VS 2015 on Windows 7 x64. – Franky Mar 10 '16 at 08:59
  • Why do you think it isn't run ? Using `g++` 5.3 every texts are displayed (http://coliru.stacked-crooked.com/a/a4b98db81858a5d2) – Garf365 Mar 10 '16 at 09:00
  • 4
    the `d`object is not linked if you have have activated some optimization. These optimizations are activated if you compile in Release mode. – norisknofun Mar 10 '16 at 09:01
  • 1
    Did you try in debug mode ? – Ilya Mar 10 '16 at 09:02
  • I'd run it in Debug mode. – Franky Mar 10 '16 at 09:04
  • @norisknofun: Are you sure? It is allowed to lazily initialize globals from other Translation Units, but every global in the TU of `main` must be initialized before `main` is called. – MSalters Mar 10 '16 at 09:07
  • 1
    well the compilation step evaluates _all_ source code. But at the link step, the linker starts from the `main` method and gathers the _needed_ code. So, we can see the `d` global variable is not used any where. So there is no reason to include this code. In DEBUG mode, all is linked but his mainly depends of the linkage options. – norisknofun Mar 10 '16 at 09:12
  • Similar issues/workarounds discussed [here](http://stackoverflow.com/questions/1229430/how-do-i-prevent-my-unused-global-variables-being-compiled-out), though in that case the problem seemed to be that `d` was in a library, rather than the main executable - is that a detail you're neglecting to mention, franky. thinking it unimportant? – Tony Delroy Mar 10 '16 at 09:19

0 Answers0