Search code examples
c++classvisual-c++publicref

How to make a public variable from a "public ref class" in c++?


How do you allow a variable to be at public/global scope of a "public ref class"?
Visual C++ [2010]
In my main DLL main.h:

namespace fdll {

 public ref class foo
 {
   public:
     int bar(int num);
  };

}

In my DLL main.cpp:

#include "main.h"
int fdll::foo::bar(int num)
{
  return num;
}


In another project:

#using <main.dll>
#include "main.h"
fdll::foo f; <--- error wtf
int main()
{
  Console::WriteLine(fdll.bar(2));
  return 0;
}


Error given:
error C3145: 'f' : global or static variable may not have managed type 'fdll::foo'
may not declare a global or static variable, or a member of a native type that refers to objects in the gc heap


Solution

  • Global variables are not supported for CLR objects, as stated here.

    Create a global class and use static to imitate global variable or only declare CLR variables in function scope.