Boost与ASIO的关联及独立ASIO在CMake项目中的使用方法
独立ASIO与Boost的关系说明及解决方案
首先明确:独立版ASIO本身不依赖Boost,但官网的示例代码多是和Boost版本ASIO共用的,所以会用到Boost库的辅助组件(比如boost/array、boost/bind、shared_ptr这些)。你完全可以用C++标准库的替代组件来替换这些依赖,不需要引入Boost。
具体替换方案
boost/array.hpp:用C++11及以上标准库的std::array替代,头文件改为<array>boost/bind/bind.hpp:用C++11的std::bind或者lambda表达式替代,头文件改为<functional>shared_ptr.hpp:用C++11的std::shared_ptr替代,头文件改为<memory>
CMake项目集成独立ASIO的正确步骤
- 把下载的独立ASIO解压后,将
asio/include目录复制到你的CMake项目中(比如放到third_party/asio/include) - 在CMakeLists.txt中添加包含目录:
include_directories(${PROJECT_SOURCE_DIR}/third_party/asio/include) - 确保编译时启用C++11及以上标准,添加:
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) - 编译时定义
ASIO_STANDALONE宏,告诉ASIO不要依赖Boost,CMake中可以这样设置:add_definitions(-DASIO_STANDALONE)
示例代码修改示例
原示例片段:
#include <boost/array.hpp> #include <boost/bind/bind.hpp> #include <asio.hpp> void handle_read(const boost::system::error_code& error, size_t bytes_transferred, boost::shared_ptr<asio::ip::tcp::socket> socket) { // ... }
修改为标准库版本:
#include <array> #include <functional> #include <memory> #include <asio.hpp> void handle_read(const asio::error_code& error, size_t bytes_transferred, std::shared_ptr<asio::ip::tcp::socket> socket) { // ... } // 调用bind的地方替换为std::bind socket->async_read_some(asio::buffer(buf), std::bind(&handle_read, std::placeholders::_1, std::placeholders::_2, socket));
修改后,项目就完全基于独立ASIO和C++标准库,不再依赖Boost。
内容的提问来源于stack exchange,提问作者JuWe
相关产品推荐
相关产品推荐

