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.
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 with extern
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.
You should only declare globals in a header. They should be defined in an implementation (source) file.
In your header you should have:
// commonHeader.h
extern int commonInt; // global *declaration*
and then in one of your implementation files you should have:
// some_file.cpp
int 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.