user2549764
user2549764

Reputation:

Conflict between global variables c/c++

I'm using two files ".h" in which there are 3 global variables with the same names.

We suppose to have these files:

When I compile C.h, I have an error cause of the conflict for same variables name.

I don't want to modify their names because They are inside public libraries (I would like to use them as they are!). This is my problem. Can someone help me? Thanks.

Upvotes: 1

Views: 2137

Answers (3)

kebs
kebs

Reputation: 6707

First, header files (".h") never get "compiled", strictly speaking, so there is no such thing as When I compile C.h. Only .cpp files, which of course include these header files get compiled.

Second, if your program needs to include the two header files that reference different variables that have the same name, then you probably have some bad design problem.

Third, I think (?, don't use unions very much...) that you need to define a name for a union.

Otherwise, a solution could be to define different namespaces to distinguish the two:

// A.h
namespace aa {
    union myType { int m1; float m2; }
    myType var1;
}

.

// B.h
namespace bb {
    union myType { int m1; float m2; }
    myType var1;
}

.

// C.cpp
#include "A.h"
#include "B.h"

...
    aa::var1.m1 = 1;
    bb::var1.m1 = 2;

Upvotes: 2

AngeloDM
AngeloDM

Reputation: 417

Try this:

LIB_FILE.H

extern union_type var1; // declaration
extern union_type var2; // declaration 

LIB_FILE.cpp

union_type var1;  // definition
union_type var2;  // definition

FILE A.H

#include "LIB_FILE.H"

FILE B.H

#include "LIB_FILE.H"

FILE C.H

#include "A.H"
#include "B.H"

You need to distinguish declaration from definition of the global variables.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182763

Quarantine each public library so that you don't need to include both header files in any single file. Files may use one library or they may use the other, but not both. You will need to create wrappers for functionality that you need, wrapping whichever library is easiest to wrap and using your wrapper, instead of the library directly, in code that uses the other library.

Upvotes: 6

Related Questions