link 使用来自 boost 的 random_device 时出错

link error when using random_device from boost

我已经使用 brew 在 MacOSX 10.15 boost 上安装,一切正常,除了 random_device。

这是我写的:

#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/discrete_distribution.hpp>
#include <boost/random/random_device.hpp>

int main() {
    boost::random::random_device rand_dev;
    boost::mt19937 gen(rand_dev());
    double probabilities[]{0, 0.99, 0.01, 0};
    boost::random::discrete_distribution<> dist(probabilities);
    std::cout << dist(gen);

    return 0;
}

这是我从编译器那里得到的:

Undefined symbols for architecture x86_64:

"boost::random::random_device::random_device()", referenced from: _main in main.cpp.o

"boost::random::random_device::~random_device()", referenced from: _main in main.cpp.o

"boost::random::random_device::operator()()", referenced from: _main in main.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)

我正在使用 CMake 链接它。而且我已经将它安装在 Ubuntu 18 上并遇到了同样的链接错误。

这是我的 CMake 的一部分:

find_package(Boost 1.72)  

if(Boost_FOUND)
     include_directories(${Boost_INCLUDE_DIRS})
     target_link_libraries(test_boost ${Boost_LIBRARY_DIR}) 
endif()

将 -lboost_random 添加到链接器输入作为编译器命令行参数:

g++  -o  test  test.cpp  -lboost_random

使用以下代码编辑您的 CMakeLists.txt:

find_package(Boost 1.72 COMPONENTS random)
if(Boost_FOUND) 
    include_directories(${Boost_INCLUDE_DIRS}) 
    target_link_libraries(test_boost ${Boost_LIBRARIES}) 
endif()