3

I have a class that defines some arrays.

Points.hpp

class Points {

public:

    static constexpr std::array< double, 1 > a1 = { {
            +0.0 } };

    static constexpr std::array< double, 2 > a2 = { {
            -1.0 / std::sqrt( 3.0 ),
            +1.0 / std::sqrt( 3.0 ) } };

};

My main file then uses these arrays.

main.cpp

#include "Points.hpp"

int main()
{
    // Example on how to access a point.
    auto point = Points::a2[0];

    // Do something with point.
}

When I compile my code, using C++11 and g++ 4.8.2, I get the following linker error:

undefined reference to `Points::a2'

I attempted to create a Points.cpp file so that the compiler can create an object file from it.

Points.cpp

#include "Points.hpp"

But that did not fix the linker error.

I was under the impression that it was possible to initialize variables as static constexpr in C++11 in the class declaration, and then access them the way I'm doing it, as shown in this question: https://stackoverflow.com/a/24527701/1991500

Do I need to make a constructor for Points and then instantiate the class? What am I doing wrong?

Any feedback is appreciated! Thanks!

8
  • Did you add the path of Points.hpp to your header path for compiler? Commented Sep 21, 2014 at 0:42
  • Points.hpp is included in main.cpp. Commented Sep 21, 2014 at 0:52
  • You need to provide a definition for static data members if they're odr-used. Commented Sep 21, 2014 at 0:58
  • What do you mean @dyp? Should I not initialize them in the header file? Commented Sep 21, 2014 at 1:00
  • That is not the problem. A static data member is only declared inside the class body (declare => the name exists), it is defined outside the class body (define => associate an object with the name). The initialization of static data members within the class body is a strange feature that allows the compiler to use the value of the variable (at compile-time), without having to query the value from the actual object. Commented Sep 21, 2014 at 1:04

1 Answer 1

2

As per @dyp suggestion, I looked into the definition of static data members.

My problem requires me to define the static member variables of my Points class.

Following the examples in these questions:

Is a constexpr array necessarily odr-used when subscripted?

and

Defining static members in C++

I need to add:

// in some .cpp
constexpr std::array< double, 1 > Points::a1;
Sign up to request clarification or add additional context in comments.

1 Comment

The first thread you linked to is talking about built-in arrays , so it's not relevant to the std::array case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.