In the process of changing some code, I have spilt some functions into multiple files. I have the files controls.cpp
and display.cpp
and I would like to be able to have access to the same set of variables in both files. I don't mind where 开发者_Go百科they are initialized or declared, as long as the functions in both files can use them.
This was not an issue when the functions were in the same file, but now it seems almost impossible after an hour of googling and trying various things.
Define the variable in one file like:
type var_name;
And declare it global in the other file like:
extern type var_name;
use those variables as extern
i.e.
extern int i;
in another file declare same as normal global variable...
int i;//global
Create two new files:
- Something like
Globals.h
and declare all variables like:extern type name;
- btw remember include guards.
- Something like
Globals.cpp
and declare variables like:type name;
Then add #include "Globals.h"
at the top of:
Globals.cpp
controls.cpp
display.cpp
You may then want some functions to initialise them.
Essentially all you have to do is declare the variable once in one code file, and declare it in the others as extern (making sure NOT to initialize it when you are declaring it extern, or some compilers will ignore the extern keyword, giving you compiler errors.)
The simplest way to do this is to use a macro in a header file, like such:
#pragma once
#ifdef __MAIN__
#define __EXTERN(type, name, value) type name = value
#else
#define __EXTERN(type, name, value) extern type name;
#endif
and then declare your variables in that same header file, like such:
__EXTERN(volatile int, MyVolatileInteger, 0);
from any ONE file in the project, include the header file, like such:
#define __MAIN__
#include "Globals.h"
from all the rest, just simply include it normally, like such:
#include "Globals.h"
Presto, you're done. Variables only declared once, and initialized in-line. This is very maintainable, and saves you the trouble of having to declare everything twice.
All of the declarations you want visible in multiple compilation units (.cpp files), should go into a header file that you include in all places that need to use the variable, type, class, etc.
This is vastly better than extern, which essentially hides your intention to share the declaration.
精彩评论