I have a Visual C++ solution, which consists out of 3 projects.
One of these projects, project “A” is used by both other projects and it has some global data which should always be the same.
However when I link project A into both other projects it seems that two instances of project A are working on different data.
Can this be the case and how can I set up the linking process to prevent this from happending?
— Update to make things more clear
- Project 1 -
main () {
init();
test();
}
- Project 2 -
test () {
cout << get_data();
}
- Project A -
int data;
init() {
data = 123;
}
get_data() {
return data;
}
As you can see in this exaple I am initializeing the data of project A in the first project and I am accessing it from the second project. My observation is that the data is not initialized when the acces from the second project takes place.
Both projects A and 2 are linked statically into project 1 so the output is a single executable.
The symbols from project A in the static library are linked into both project 1 and project 2, separately. Getting them merged involves compiler-specific mechanisms.
Basically, you must make project 2 re-export project A’s symbols, and have project 1 import those instead of importing project A directly.
If you can’t do that (e.g. because you don’t have control over either project 1 or 2), you must write workarounds inside project A. One option (the easiest usually) is to convert project A to a dynamic library. Then both project 1 and 2 load the same instance of project A and the data is shared.
Another option is to change project A so that it doesn’t have a global variable, but instead registers a process-global data item that contains the data you want; for example, you could abuse the local atom table[1] to store a pointer to dynamic memory.
[1] http://msdn.microsoft.com/en-us/library/windows/desktop/ms649053%28v=vs.85%29.aspx#_win32_Integer_Atoms