-
Global struct in MFC app
Hello,
I have an MFC application that has many different classes which need to access a struct filled with particular values. All of the classes need to have access to these values so I thought that this would be an opportunity to use a global variable in a decent way. However I put the struct declaration
Code:
struct some_struct{
int one;
int two;
int three;
};
in the
Code:
class CMyApp : public CWinApp
header and then make an instance of that struct in the implementation file
Code:
some_struct instanceOfStruct;
However,
Code:
extern some_struct instanceOfStruct;
is only working for me in a few classes and other times it will tell me,
Code:
error C2146: syntax error : missing ';' before identifier 'instanceOfStruct'
error C2065: 'instanceOfStruct' : undeclared identifier
Any thoughts? I know this is poorly worded, and I apologize for that, but I'm just too tired to try and fix it right now. Thank you for any help you might be able to give me. Also, criticism and better ways to do this are welcome.
-
It sounds like, based on what I see here, that some files don't recognize the name some_struct as a typename. Do all of these files include the appropriate header?
-
Make the "global" variable/struct/whatever a member of the application class. Then anywhere in your code you can access it using AfxGetApp().
I don't know if this technique is frowned upon, or bad practice. It worked for me.
-
globals.h
Code:
#ifndef GLOBALS_H
#define GLOBALS_H
struct some_struct
{
int one;
int two;
int three;
};
class CGlobals
{
public:
static some_struct instanceOfStruct;
// friend class some_class;
#endif
extern CGlobals globals;
globals.cpp
Code:
#include "globals.h"
CGlobals globals;
int CGlobals::instanceOfStruct.one = 1;
...
access with:
Code:
#include "globals.h"
globals.instanceOfStruct