CodeKingPlusPlus
CodeKingPlusPlus

Reputation: 16081

C++ namespaces and multiply defined variables

I have two C++ namespaces as follows:

#ifndef TRANS_H
#define TRANS_H
namespace Trans
{
   double Delta[3];
   double calcDeltaPositions();
   //and more that I will leave out for simplicity
};
#endif

#ifndef SPACE_H
#define SPACE_H
namespace Space
{
   double vels[3];
   void calcAccel(double DeltaVal[3]);
};
#endif

Now I have a main.cpp file:

#include "Trans.h"
#include "Space.h"
int main()
{
    double pos = Trans::calcDeltaPositions();
    Space::calcAccel(Trans::Delta);
    return 0;
}

I keep getting an error claiming that Delta is a multiply defined in main.o and Trans.o How could this be since I have only declared Delta to exist in Trans?

Upvotes: 2

Views: 381

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258588

If the files Trans.h and Space.h is included in multiple translation units (cpp files - in your case, both main.cpp and trans.cpp), you will have defined the variable multiple times, thus breaking the one definition rule.

If you want a global, you'll need to declare the variable as extern and define it in a single implementation file.

If you want a copy of the variable for each translation unit (probably not), you can declare it static.

How could this be since I have only declared Delta to exist in Trans?

Actually, you didn't. That's a definition, not a declaration.

//Trans.h
namespace Trans
{
    extern double Delta[3];
};

//Trans.cpp
double Trans::Delta[3];

Upvotes: 9

Related Questions