Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one avoid accidentally redeclaring global constants in C++?

I have a template matrix class class defined in a header called "Matrix.h".

Certain matrices are used repeatedly in my program. I thought that I would define these in the "Matrix.h" header file, like so:

const Matrix<GLfloat> B_SPLINE_TO_BEZIER_MATRIX(4, 4, values);

When I do this g++ complains that I redefined the constant in question. This happens because I include Matrix.h in two different source files. When the object files for these are compiled, both end up with a definition of the matrix above, causing the error message.

My question is how do I avoid this situation? I want a constant that is accessible to more than one file, but I don't know where to put it.

like image 602
fluffels Avatar asked Dec 10 '22 21:12

fluffels


1 Answers

You avoid it by:

  • Declaring it extern in the header. A symbol can be declared any number of times.
  • Defining it in the implementation, only once.
like image 106
unwind Avatar answered Jan 25 '23 22:01

unwind