Scott Tiger
Scott Tiger

Reputation: 488

Undefined reference to my class static field errors from gcc atomic headers

all!

I have a static atomic field, defined like this:

private:
  static std::atomic<int> total_requests_;

in a class named FcgiRequestPool.

In this class method i use it:

FcgiRequestPool::FcgiRequestPool() {
  // the first born pool will set total request counter to zero.
  static std::once_flag total_requests_init_flag;
  std::call_once(total_requests_init_flag, []() {
    total_requests_ = 0;
  });
}

I don't see anything criminal here so far. And when i compile it...

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++14 -O2 -Wall -Wextra -pedantic -Werror )

I get this errors:

CMakeFiles/libdolly.dir/kanaria/FcgiRequestPool.cpp.o: In function `std::__atomic_base<int>::store(int, std::memory_order)':
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.3/include/g++-v4/bits/atomic_base.h:478: undefined reference to `FcgiRequestPool::total_requests_'
CMakeFiles/libdolly.dir/kanaria/FcgiRequestPool.cpp.o: In function `std::__atomic_base<int>::fetch_add(int, std::memory_order)':
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.3/include/g++-v4/bits/atomic_base.h:618: undefined reference to `FcgiRequestPool::total_requests_'
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.3/include/g++-v4/bits/atomic_base.h:618: undefined reference to `FcgiRequestPool::total_requests_'
CMakeFiles/libdolly.dir/kanaria/FcgiRequest.cpp.o: In function `FcgiRequest::FcgiRequest(std::shared_ptr<FcgiRequestPool>)':
/home/rakul/play/kanaria/git/src/kanaria/FcgiRequest.cpp:13: undefined reference to `FCGX_InitRequest'
CMakeFiles/libdolly.dir/kanaria/FcgiRequest.cpp.o: In function `FcgiRequest::FinishRequest()':
/home/rakul/play/kanaria/git/src/kanaria/FcgiRequest.cpp:30: undefined reference to `FCGX_Finish_r'

Since I obviously made a brief googling, before you suggest adding -latomic, this is my humble test:

rakul@lucky-star /tmp $ cat test.cpp
#include <atomic>
#include <iostream>

int main() {
    std::atomic<int> i(42);
    std::cout << i.fetch_sub(1) << std::endl;
    return 0;
}
rakul@lucky-star /tmp $ g++ --std=c++14 test.cpp
rakul@lucky-star /tmp $ ./a.out 
42
rakul@lucky-star /tmp $ 

Which, I think, should prove that on my system (gentoo, gcc 4.9.3 p1.4) atomics compile, work and don't require additional libs.

Any help is very welcome. Thank you!

Upvotes: 3

Views: 939

Answers (1)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31173

You only added the static member variable to the definition of the class. You have to also actually define the static variable in a implementation file.

Add this to a .CPP file:

std::atomic<int> ClassName::total_requests_;

Without this the variable is not actually allocated any storage or instantiated and cannot be used.

Upvotes: 4

Related Questions