I’m working on an MFC application, I want to make a global string variable to be shared between all the actions in the application, I made a static string variable inside a header file but when I attempt to access it inside one of the actions this compiler error arises:
error C3381: 'comp' : assembly access specifiers are only available in code compiled with a /clr option
This is my header file, inside it is the class:
//Shared_Variable.h
class comp
{
comp() { } // private default constructor
public:
static CString myValue;
};
and I used it inside one of my actions as follows:
void CCalculatorDlg::OnBnClickedButton1()
{
comp::myValue="1"; ----->accessing the static member of my class
LPCTSTR btn_title=_T("1");
SetDlgItemText(IDC_EDIT1,btn_title );
}
A few possibilities at first glance;
Additionally, declaring a static member inside a class within a header like that requires that you have a single .cpp file that defines the single instance of that member. So you can declare it in the header as:
but you have to do this within Shared_Variable.cpp:
Without this, you’ve defined a static variable but not told C++ where to stick it in memory. Since header files are pulled in as dependencies to (potentially) multiple CPP files, you always have to make sure that anything static is pinned to exactly one CPP file, which is what the above code snippet is about.
An alternate way to make a simple static variable is to declare in your header file:
and in the corresponding CPP file (any CPP file, really, it doesn’t technically even have to include the header file, although it’s a good idea):
Does any of that help?