Search code examples
c++boostclangc++14c++-chrono

Using boost::chrono::system_clock to get time causes linker error


I have program which is linking to system,chrono and thread in boost. But simply adding auto now = boost::chrono::system_clock::now() gives me a linker error.

Following is my main.cpp

#include <iostream>
#include <boost/chrono.hpp>
#include <boost/circular_buffer.hpp>

int main(int argc, char* argv[]) {
   boost::circular_buffer<int> test_ring;
   test_ring.resize(10);
   std::cout << "Boost ring size is" << test_ring.size() << std::endl;
   
   // Below line of code causes linker error while I am well able to use boost componenets as you can see above
   auto now = boost::chrono::system_clock::now();
   return 0;
}

Following is my CMakelists.txt

cmake_minimum_required(VERSION 3.4)
project(TestProgram)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")

find_package(Boost REQUIRED COMPONENTS system chrono thread)
include_directories(${Boost_INCLUDE_DIRS})

add_executable(TestProgram TestProgram.cpp)

I get the following linker error:

Undefined symbols for architecture x86_64:
  "boost::chrono::system_clock::now()", referenced from:
      _main in TestProgram.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [TestProgram] Error 1
make[1]: *** [CMakeFiles/TestProgram.dir/all] Error 2
make: *** [all] Error 2

Question:
What am I doing wrong? Am I missing any boost components to link to? As you can see, I am able to link to other Boost components like boost/circular_buffer on my machine, it is just that boost::chrono::system_clock does not work.

Environment:
I am on macOS Catalina 10.15.7 wiht the following clang compiler.

Apple clang version 12.0.0 (clang-1200.0.32.21)
Target: x86_64-apple-darwin19.6.0
Thread model: posix

Solution

  • After add_executable, add target_link_libraries:

    add_executable(TestProgram TestProgram.cpp)
    target_link_libraries(TestProgram ${Boost_LIBRARIES})