i have an global variable in an common header file. Eg
commonHeader.h
int commonInt = 0;
i have 3 dll projects in which i want to use it , so i include above header, but it give me error symbol defined multiple times , #pragma once also did't work.
if i make above variable extern , and define it in my exe i get linker errors in my dll.
all my dll need above header.one of my dll need other 2 dll's header file (probably making multiple include of syombol)
how i can resolve above issue , i want only one variable across dll and exe.
i am using VS 2010 prof on windows 7.
thanks in advance.
- 2Do you absolutely need a global variable? Why?tmaric– tmaric2013-01-07 13:45:04 +00:00CommentedJan 7, 2013 at 13:45
2 Answers2
You're violating the One Definition Rule (§ 3.2) by having that global variable definition in a header file. Instead you were correct to only declare it in a header file withextern and then have the definition in a single implementation file.
But in order to have this work with dlls you also have to declare it as exported by the exe and imported by the dlls with__declspec(dllexport) and__declspec(dllimport), using appropriate macros to choose the right__declspec depending on whether you're compiling the exe or the dlls.
Comments
You should onlydeclare globals in a header. They should bedefined in an implementation (source) file.
In your header you should have:
// commonHeader.hextern int commonInt; // global *declaration*and then inone of your implementation files you should have:
// some_file.cppint commonInt = 0; // global *definition* (and initialisation)Of course global variables should be avoided wherever reasonably possible - excessive use of globals is a "code smell", but sometimes it can not be avoided.
Comments
Explore related questions
See similar questions with these tags.