Paul Masri-Stone
Paul Masri-Stone

Reputation: 3139

Accessing a static atomic data member causes a linker error

How should a static atomic variable be accessed without causing a linker error?

I've reduced my code example to the following:

#include <iostream>
#include <atomic>

class MyClass
{
public:
    static std::atomic_bool onOrOff;
};

std::atomic_bool onOrOff(false);

int main(int argc, const char * argv[]) {
    std::cout << "It is: " << (MyClass::onOrOff? "on": "off") << "\n";
    return 0;
}

This results in the following linker error (MaxOS X 10.11, XCode 7.2):

Undefined symbols for architecture x86_64:
  "MyClass::onOrOff", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

NB: There are no build errors if I remove the line in main() accessing MyClass::onOrOff, so I think that rules out problems with compiler options.

Upvotes: 0

Views: 258

Answers (2)

NathanOliver
NathanOliver

Reputation: 180935

You forgot that onOrOff is a scoped name to MyClass. You need

std::atomic_bool MyClass::onOrOff(false);

Live Example

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249394

This:

std::atomic_bool onOrOff(false);

Should be:

std::atomic_bool MyClass::onOrOff(false);

As it stands you have declared two different onOrOff variables, one inside the class and one outside. And only allocated storage for one.

Upvotes: 4

Related Questions