Theo Walton
Theo Walton

Reputation: 1105

Initializing static member makes compilation work... but why

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?

Upvotes: 2

Views: 40

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

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.

Upvotes: 1

Related Questions