0

In my code I have classes with the following structure (I use c++11):

class Foo {
public:
static constexpr double A = 3.0;
//....other....
};

Sometimes I have linker error because the static variable is not defined in cpp file. But not always. I don't understand the rule here, when is it needed to declare the static field in cpp and when not?

greywolf82
  • 21,813
  • 18
  • 54
  • 108
  • *"Sometimes ... But not always."* Do you have an example that consistently reproduces the error? What you have shown looks correct to me. – 0x5453 May 20 '20 at 16:14
  • This question has been closed but the other one doesn't reply to the question. Reading the reply it seems you need to always declare the out of class variable before c++17, but it's wrong because I have several examples where I didn't do it and it works. – greywolf82 May 20 '20 at 16:21
  • 1
    @greywolf82 - Did you skim the bit where it says ODR use? – StoryTeller - Unslander Monica May 20 '20 at 16:24
  • If including the header in more than once place, you need to put the definition in the cpp file, otherwise you're effectively defining the variable twice, and will get a linker error along the lines of multiple defined symbols. #pragma once will prevent you from _declaring_ a variable multiple times, but not from _defining_ it multiple times. I suspect the times it has worked will be where the header is only included once throughout the codebase. – castro May 20 '20 at 17:46

0 Answers0