Boost下载
https://www.boost.org/
编译Boost
将Boost压缩包解压,并通过命令行窗口进入到Boost源码根目录
bootstrap.bat mingw //注意,对于某些版本的Boost,可能不需要明确指定mingw,因为bootstrap脚本会自动检测可用的编译器
b2 toolset=gcc --build-type=complete --prefix=<install-dir> install
toolset=gcc:指定编译器工具集。 --stagedir=stage-directory:指定构建完成的库文件存放的目录,默认stage文件夹。 --prefix=install-dir:指定库文件和头文件的安装位置。 --build-type=complete:表示执行完整的编译和测试。
如果你只想编译特定的一些库,可以使用–with-参数。例如,要编译system和filesystem库,可以运行:
b2 toolset=gcc --with-system --with-filesystem
编写CMakeLists.txt文件
cmake_minimum_required(VERSION 3.25)
project(BoostExample)
# 设置C++标准
set(CMAKE_CXX_STANDARD 14)
# 设置Boost库的根目录(应指向 Boost 的安装根目录)
set(BOOST_ROOT "D:/3rdparty/boost_1_85_0")
# 禁用搜索系统路径
set(Boost_NO_SYSTEM_PATHS ON) # 非常重要,否则会导致找不到 Boost 库
# 查找Boost库,指定需要的组件
# find_package(Boost REQUIRED COMPONENTS filesystem regex)
find_package(Boost REQUIRED)
# 输出 Boost 的相关信息
message("Boost version: ${Boost_VERSION}")
message("Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
message("Boost_LIBRARY_DIRS: ${Boost_LIBRARY_DIRS}")
message("Boost_LIBRARIES: ${Boost_LIBRARIES}")
# 包含Boost头文件目录
include_directories(${Boost_INCLUDE_DIRS})
# 链接Boost库目录
link_directories(${Boost_LIBRARY_DIRS})
# 创建可执行文件
add_executable(BoostExample main.cpp)
# 链接Boost库
target_link_libraries(BoostExample ${Boost_LIBRARIES})
编写main.cpp测试文件
#include <boost/any.hpp>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
using namespace boost;
int main()
{
typedef vector<boost::any> many;
many a;
a.push_back(2);
a.push_back(string("test"));
for (unsigned int i = 0; i < a.size(); ++i)
{
cout << a[i].type().name() << endl;
try
{
int result = any_cast<int>(a[i]);
cout << result << endl;
}
catch (boost::bad_any_cast& ex)
{
cout << "cast error:" << ex.what() << endl;
}
}
getchar();
return 0;
}
测试命令(Windows、MinGW)
cd build
cmake -G "MinGW Makefiles" ..
mingw32-make