开发者

How to use global variables across projects in a solution?

I have a C++ solution in which there is a global variable which I want to be accessible across projects in the solution file. I know this is not recommended but what is the best way to do this开发者_如何学Python?


Define the variable once, in the file that originally has the global variable and declare the variable extern in every file that uses it.

File 1:

int GlobalVariable;

int main(int argc, char *argv[]) {
    // blablabla
}

File 2:

extern int GlobalVariable;

int somefunc(void) {
    // blablabla
}

File 3:

extern int GlobalVariable;

// blablabla


All projects in a solution - ie you're building several dlls, grouped togetehr in a solution?

If that's the case then you have the problem that the a global in one dll cannot easily be read by another dll. You will need write the global to shared memory and have all dlls read from there.

An alternative aproach is easy: create a dll jsut to hold your shared variables and wrap them in a pragma. eg from this link:

#pragma data_seg (".myseg")
   int i = 0; 
   char a[32]n = "hello world";
#pragma data_seg()

then each of your different dlls can link with the 'data dll', the data dll will contain a single instance of the variables no matter how many times its loaded or in which process. Performance counters use this technique to quickly pass data counters between the process that generates the data and perfmon.exe that reads and displays it.


There is a difference between Translation Unit and Project (specifically in Visual Studio).

In C and C++ you can make a global variable only accessible from the file in which it's declared by using the static keyword in front of the declaration. Globals that don't use the static keyword are accessible from any C or C++ file compiled into the program.

But frankly your question is not clear. When you say Global there can be lots of perspectives to it, as Wikipedia says in the article on Global Variables:

The C language does not use the term global, though in a small program contained in a single file it is possible to get the same effect by declaring a variable outside all functions (see below). However, such a variable should be called external, not global, since its scope is limited to the single file.

But, you may go through these links to see if you can solve the your specific problem:

Global variables/functions across different projects

Shared global variable in C++ static library

How to implement process-global variable in C++

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜