Create global variables/static class entries RRS feed

  • Question

  • Hi,

    I am trying to do something, that used to be very simple.
    I wish to create some global variables that I can use within a CLR form, and in my .cpp and .h files in the same project.  I was told the new way is to create a class with STATIC variables.  So I have done this.  However now I find I am either getting LNK2005/  LNK1169: one or more multiply defined symbols found errors or I get error C2039: 'global_vars' : is not a member of 'myspace' errors.

    To test this I have created a simple CLR form with 1 menuitem, and when I select the menuitem I wish to set this value.

    In the file Form1.h I have created this code:
      #include "my_code.h"
     . . .
      private: System::Void TestToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e)  {
                     myspace::global_vars.var1 =1;

    I have created  two files; my_code.h and my_code.cpp.
    my_code.h has the following:
    #pragma once
    #include "Form1.h"
    namespace myspace  {
      class   GlobalVars          {
                   public  :       int    var1;     };
      GlobalVars  global_vars;                              // KEY LINE 1

    my_code.cpp has the following
    #include "my_code.h"
    namespace myspace
         GlobalVars  global_vars;                        // KEY LINE 2.

    If I have Key Line 1 uncommented  and Key Line 2 commented then I get the error
    1>test1.obj : error LNK2005: "class myspace::GlobalVars myspace::global_vars" (?global_vars@myspace@@$$Q3VGlobalVars@1@A) already defined in my_code.obj

    If I have Key Line 1 commented and Key Line 2 uncommented then I get the error.
    e:\test1\Form1.h(105) : error C2039: 'global_vars' : is not a member of 'myspace' 
    against the line  myspace::global_vars.var1 =1; in Form1.h.


    Tuesday, December 30, 2008 10:54 PM


  • Hi,

    I worked around this by creating two  file "global_externs.h"  and "globals.h"
        //   globals.h
        #define my_globals
        int     global1;
        int     global2;

        //  global_externs.h 
        #ifndef my_globals
        #define my_globals
        extern  int     global1;
        extern  int     global2;

    The file globals.h was included in only 1 source file, and was put second in the include list, after including stdafx.h.  This meant it was included before the file "global_externs.h" which was included in all source files.

    Cheers Zach

    • Marked as answer by zach99 Monday, January 5, 2009 11:26 PM
    Monday, January 5, 2009 11:20 PM