Reputation: 3139
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
Reputation: 180935
You forgot that onOrOff
is a scoped name to MyClass
. You need
std::atomic_bool MyClass::onOrOff(false);
Upvotes: 1
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