gpt4 book ai didi

c++ - 如何使用CMake自动链接Boost库

转载 作者:行者123 更新时间:2023-12-02 10:21:00 27 4
gpt4 key购买 nike

project(learn)

cmake_minimum_required(VERSION 3.11)

set(CMAKE_CXX_STANDARD 17)

if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
message("Current OS is Linux")
include_directories("/mnt/e/c++/boost_1_72_0")
link_directories("/mnt/e/c++/boost_1_72_0/stage/lib")
link_libraries(pthread boost_thread boost_fiber boost_context)
elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
message("Current OS is Windows")
include_directories("E:/c++/boost_1_72_0")
link_directories("E:/c++/boost_1_72_0/stage/lib")
endif(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")

add_executable(learn_asio learn_asio.cpp)

learn_asio.cpp:
#include <boost/asio.hpp>
#include <boost/fiber/all.hpp>
#include <boost/thread.hpp>
#include <iostream>

using boost::asio::async_write;
using boost::asio::buffer;
using boost::asio::io_context;
using boost::asio::use_future;
using boost::asio::ip::make_address;
using boost::asio::ip::tcp;
using boost::fibers::async;
using boost::fibers::fiber;
using boost::system::error_code;

int main(){
io_context ioc;
tcp::socket socket(ioc);

tcp::endpoint ep(make_address("192.168.1.20"), 80);

auto ret_f = socket.async_connect(ep, boost::asio::use_future);

boost::thread_group t;
t.create_thread([&ioc]() {
ioc.run();
std::cout << "jfiejf" << std::endl;
});

ret_f.wait_for(std::chrono::seconds(3));

t.join_all();

return 0;
}

我的图书馆文件夹:
boost library folder

通过上面的代码,我可以成功地构建代码。但是我讨厌代码:
link_libraries(pthread boost_thread boost_fiber boost_context)

在linux平台上。为什么在Windows平台上不需要它?我记得Linux也可以自动链接库。
我该如何实现?

最佳答案

Boost docs:

Auto-Linking

Most Windows compilers and linkers have so-called “auto-linking support,” which eliminates the second challenge. Special code in Boost header files detects your compiler options and uses that information to encode the name of the correct library into your object files; the linker selects the library with that name from the directories you've told it to search.

The GCC toolchains (Cygwin and MinGW) are notable exceptions; GCC users should refer to the linking instructions for Unix variant OSes for the appropriate command-line options to use.


请注意,已知自动链接功能有时会失败(例如,使用非标准设置安装Boost库时)。您可以定义 BOOST_ALL_NO_LIB以在Windows上禁用该功能。
但是,您不应该将Boost路径硬编码到CMakeLists.txt中。最好使用与平台无关的 find_package:
set( Boost_USE_STATIC_LIBS OFF )
set( Boost_USE_MULTITHREADED ON )
set( Boost_USE_STATIC_RUNTIME OFF )

find_package( Boost 1.72.0 COMPONENTS thread fiber context )

if ( Boost_FOUND )
include_directories( ${Boost_INCLUDE_DIRS} )
link_libraries( learn_asio ${Boost_LIBRARIES} )
else()
message( FATAL_ERROR "Required Boost packages not found. Perhaps add -DBOOST_ROOT?" )
endif()

关于c++ - 如何使用CMake自动链接Boost库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60180616/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com