【问题标题】:Using boost::chrono::system_clock to get time causes linker error使用 boost::chrono::system_clock 获取时间会导致链接器错误
【发布时间】:2021-02-08 19:10:03
【问题描述】:

我有一个链接到系统、计时和线程的程序。但只需添加 auto now = boost::chrono::system_clock::now() 就会出现链接器错误。

以下是我的 ma​​in.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;
}

以下是我的 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)

我收到以下链接器错误

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

问题:
我究竟做错了什么?我是否缺少要链接的任何增强组件?如您所见,我可以在我的机器上链接到其他 Boost 组件,例如 boost/circular_buffer,只是 boost::chrono::system_clock 不起作用。

环境:
我在 macOS Catalina 10.15.7 上使用以下 clang 编译器。

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

【问题讨论】:

  • 我更新了问题中的代码以证明我能够链接和使用boost::circular_buffer。我还可以使用其他增强组件。只是boost::chrono::system_clock::now 不起作用。奇怪!
  • circular_buffer 只是 boost 的一个标题部分。 chrono 不仅仅是标题的一部分。所以,这就解释了为什么第一个有效,而第二个无效
  • 我已经给出了完整的代码。我很想知道这段代码是否可以在其他人的机器上编译。
  • 我猜你需要target_link_libraries
  • 注意:你不需要使用boost中的任何一个库,你可以使用原生STL。

标签: c++ boost clang c++14 chrono


【解决方案1】:

add_executable之后,添加target_link_libraries

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多