Question:
Why do I get a multiple definition error in my C++ code?
James
2010-07-07 05:19:18 UTC
Hi, I'm coding a project with lots of namespaces, some of which have variables declared in them, one such example is the following namespace:

namespace normalization{


float tstar;
float bstar;
float xstar;
float vstar;
float estar;
float pstar;

void set_norm(float mpart, float q)
{
float omega = IMF::particleFunctions::omega(mpart, q);
IMF::normalization::tstar = (2.0*IMF::constants::pi)/omega;
IMF::normalization::xstar = IMF::constants::rsun;
IMF::normalization::vstar = (IMF::constants::c)/1000.0;
IMF::normalization::bstar = IMF::b0/100.0;
IMF::normalization::estar = (bstar*vstar)/IMF::constants::c;
IMF::normalization::pstar = mpart*vstar;
}
}

I can compile all my source files up to the point where i get .o files, but I can't link these files, at that point I get an error message saying multiple definition of the variables in the above namespace.

I think the problem may lie in my header file, here is the contents of the header file for the namespace listed above:

namespace normalization{

//float tstar;
//float bstar;
//float xstar;
//float vstar;
//float estar;
//float pstar;

void set_norm(float mpart, float q);
}

please could someone help me to fix this bug? If you need any further information I will try and provide it.
Three answers:
Chris C
2010-07-07 05:55:44 UTC
I think your problem is most likely in these 2 lines:

IMF::normalization::estar = (bstar*vstar)/IMF::constants::c;

IMF::normalization::pstar = mpart*vstar;



You see, it doesn't know which 'bstar' or 'vstar' to use. The one in the IMF::normalization class, or the local variable. And for that matter, neither do I.

Do you want the function to use the local 'bstar' (clarified by coding '::bstar'), or the IMF::normalization::bstar?

Ditto for the 'vstar' variable.
ISkiTheWest
2010-07-07 12:46:03 UTC
question:



1. it looks like you are showing that your header file contains commented out variable names, correct?



2. and the code that you are showing at the top of your question.. does that appear in more than one .cpp file that you are compiling into object files?



additional:

I suggest declaring in the header, and only doing the stuff in your set_norm function in the cpp. I assume this stuff will be used in other cpp's as well? Also, can you post the full error you are getting for that 'tstar not a member of norm'
gEo
2010-07-07 12:28:27 UTC
hey how about making your variables like this: float tstar,bstar,xstar,vstar,estar,pstar; <- to save memory :D


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...