C++ "multiple definitions of"....



Help for C/C++ for MVS, OS/390 C/C++, z/OS C/C++ and C/C++ Productivity Tools for OS/390

C++ "multiple definitions of"....

Postby rajj2112 » Tue Oct 05, 2010 11:59 am

Each module that includes ImageManager.h will declare a global variable named ImageManager of type class ImageManager.

So main.cpp says: Hey, I've got a global variable named ImageManager, and everyone can muck with it.
And ImageManager.cpp says: Hey, I've got a global variable named ImageManager and everyone can muck with it.

The linker says: Whoa....main and ImageManager both have variables named ImageManager. I can't be sure they are talking about the same thing here, so I'm not going to guess and risk guessing wrong. Barf.
rajj2112
 
Posts: 1
Joined: Tue Oct 05, 2010 11:50 am
Has thanked: 0 time
Been thanked: 0 time

Re: C++ "multiple definitions of"....

Postby Tim » Mon Mar 28, 2011 11:34 pm

All but one module should declare the global "extern".
Tim
 
Posts: 21
Joined: Thu Mar 24, 2011 1:00 am
Has thanked: 0 time
Been thanked: 0 time

Re: C++ "multiple definitions of"....

Postby nxkjh » Sat Nov 26, 2011 1:10 pm

You're defining identically named objects with static duration and external linkage in every translation unit that includes this .h file, which is why no two such translation units can be linked together. The include guards "the whole ifdef/define/endif" do something different.
It is also bad style to define a class and an object of that class type in a single statement.

Explain why do you want to "include it there" to see how it can be done in C++. Typical approaches, are: 1) instantiate an object of this type with auto or dynamic duration and access it by reference/smart pointer where needed 2) instantiate an object of this type with static duration in *one* translation unit and use the extern declaration in the other units that must access it, and 3) make it a Singleton and access it via static function such as ImageManager::getInstance()

By the way, I have a feeling that ImageManager::isImageUsed() and ImageManager::getImage() should be declared const, especially seeing how the latter returns a const reference. Do they modify ImageManager while obtaining that bool or that reference?
nxkjh
 
Posts: 3
Joined: Wed Nov 23, 2011 7:48 pm
Has thanked: 0 time
Been thanked: 0 time


Return to C, C++

 


  • Related topics
    Replies
    Views
    Last post