1

I have a class that changes the color of something based on button inputs. I'd like to predefine a bunch of "colors" so that a state machine can simply copy the constant structs defined in header to some variable to change colors.

I don't understand why the compiler is hunky-dory with the below code but the Linker can't deal with it. Is there a better pattern for defining constant structs? Should I just make them non-static non-const and live with it?

class ColorManager {
 public:

  ColorManager () {
  }

  // ProcessButton uses the static constexpr structs defined below
  void ProcessButton(uint8_t button_state);

 private:
  // Color_t is defined elsewhere as a struct of R, G, B fields
  static constexpr Color_t kColorWhite  = {100, 100, 100};
  static constexpr Color_t kColorRed    = {100, 0, 0};
  static constexpr Color_t kColorPurple = {100, 0, 70};

};

Edit: Here's an example error message:

src/color_manager.o: In function `ColorManager::ProcessButton(uint8_t button_state)':
color_manager.cc:(.text+0x224): undefined reference to `ColorManager::kColorWhite'
collect2: error: ld returned 1 exit status
4
  • 1
    Please provide the error message you are getting. Commented Dec 27, 2018 at 5:57
  • 1
    Where and how is "Color_t is defined elsewhere as a struct of R, G, B fields"? How is that source being linked with the final program? Commented Dec 27, 2018 at 6:08
  • It's defined in another header file that is included in the color_manger.hh Commented Dec 27, 2018 at 6:09
  • Is it defined or simply declared as a forward declaration with the definition in another source? If the latter, you would need to link the additional source. As it sits, there is nothing inherently wrong with what you have posted and where you say the struct is defined. (not even from a -std=c++11 standpoint) Commented Dec 27, 2018 at 6:14

1 Answer 1

3

Prior to C++17 those constexpr static member declarations are not defintions. You need to provide a definition in some translation unit.

Color_t ColorManager::kColorWhite;

In C++17 those would be implicitly inline variables.

Sign up to request clarification or add additional context in comments.

4 Comments

I see so if I move to C++17 all will be well? Is there any usual pattern people follow for this situation prior to C++17?
@kkemper - We would add a definition in a cpp file and proceed to compile and link it.
I was afraid of that. It just seems messy but I might have to live with it.
@kkemper - Mind you that you only need a definition if those constans are odr-used (i.e. need to have an address)

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.