2

I have 3 files:

main.cpp -

#include "test.hpp"

int main(void)
{
    test x;
    return (1);
}

test.hpp -

#ifndef TEST_HPP
#define TEST_HPP

class test
{
    static int a;

public:
    void    func(void);
};

#endif

test.cpp -

#include "test.hpp"

int test::a = 0; // removing this line makes compilation fail

void    test::func(void)
{
    a--;
}

and I compile with: clang++ *.cpp -I ., only these 3 files are in my directory.

the compilation fail message is:

Undefined symbols for architecture x86_64:
  "test::a", referenced from:
      test::func() in test-8bbfc4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

from my understanding the line:

int   test::a = 0; // removing this line makes compilation fail

was just initializing the static member a to 0, which as it is already 0 effectively means nothing.

Why should this make a difference for the compilation?

1 Answer 1

1

was just initializing the static member a to 0

No, it's not just initialization, it's the definition of the static data member. Without it you'll get the link error as you've seen.

The declaration inside the class body is not a definition...

BTW: Constant static members* and inline static members (since C++17) can be defined in the class definition.


*Note that when a const non-inline non-constexpr static data member is odr-used, a definition at namespace scope is still required, but it cannot have an initializer.

5
  • ok so for future, everytime I declare a static variable inside a class I need to define and initialize it outside the class? Or is there a way to do this within the class Commented Jan 6, 2018 at 8:43
  • @TheoWalton The const/inline static data member can be defined inside the class definition. See the link I posted for more informations. Commented Jan 6, 2018 at 8:47
  • If it is a simple type like a const integral, I believe you can define it right there. Literally put an "= 0" after the declaration right in the header file. I admit I forget the specific rules. But for more complicated types, you generally need to put it in the .cpp file.
    – Joe
    Commented Jan 6, 2018 at 8:48
  • @songyuano: What link?
    – Joe
    Commented Jan 6, 2018 at 8:49
  • @Joe Link added. Commented Jan 6, 2018 at 8:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.