Link to home
Start Free TrialLog in
Avatar of alseenu
alseenu

asked on

How to allow duplicate symbols between modules ??

Say I have two source programs A.C and B.C, which both include a header file called XX.H. I have defined
a variable 'xyz' in this header file. While linking, this gives an error like "xyz defined in A.C is duplicated in B.C".

Particularly I am using BC++4.52 compiler. Is there any
compiler/linker setting that can help me get rid of such huge no.of errors ??

Regards
Sreeni..
Avatar of sureshkumar
sureshkumar

can you give question clearly.

Hi alseenu !!
  U can have the header directive for the XX.H file like

#ifndef _XX_H
#define _XX_H

//declarations......


#endif



Now u can include this file as many times u want

ASKER CERTIFIED SOLUTION
Avatar of inpras
inpras

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Take care that you know what it means to allow multiply defined symbols.  It may mean that two global variables are created and used, and you will not be able to easily check what actually happens.

It might be better to do it properly, that is, if you want a global variable that is declared in a header file, do it like this:

in xx.h

#ifndef _XX_H
#define _XX_H

extern int xyz;

#endif

and then have xx.cpp

which has:

#include "xx.h"

int xyz;




The suggestion from akalmani looks a whole lot better then that from inpras. Avoid such settings in the linker and compiler at all cost.
Use the #defines as shown for ALL your headers. It is common practice and will be invaluable if your projects grow in size.
I agree with Jason, do not define code and global data in header files.
I agree with that too.
I aggree with Jason and akalmani and both have the most common answer: declare _shared_ variable name, then define in which .c / .cpp file (so belatly ".o"->Unix, or ".obj" file) you want it declared (in Jason it's in "xx.cpp").

If you want global for both one for each file: a.C and b.C, declare it at ".C" file-scope not in ".h". probably the linker want have it twice.
The #define pre-compiler directive doesn't solve 2 declarations (and that will happen!) one for each file. That works only for Jason solution.

Anyway, if two independent vars one on A and other in B, why don't you just use 2 diferent names ?
I haven't been clear(improving): akalmani suggest one veil and Jason really adds the whole picture.
I described 2 cases:
 - One global scope (between a.C and b.C) var, implemented in xx.C for instance
 - two global scope vars, meaning file-scope, one in a.C and other in b.C. I'm not sure but probably must be two different var names, since compiler doesn't decorate var-symbol with file name("a" or "b") so when linking they conflict (xyz from a and xyz from b).