1

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.

askedJan 7, 2013 at 13:44
vivek's user avatar
1
  • 2
    Do you absolutely need a global variable? Why?CommentedJan 7, 2013 at 13:45

2 Answers2

4

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.

answeredJan 7, 2013 at 13:48
bames53's user avatar
Sign up to request clarification or add additional context in comments.

Comments

3

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.

answeredJan 7, 2013 at 13:46
Paul R's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.