Boost的配置与使用(Windows)

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
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值