[英]How to auto-link boost libraries with CMake
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)
學習_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;
}
我的庫文件夾:
根據上面的代碼,我可以成功構建我的代碼。 但我討厭代碼:
link_libraries(pthread boost_thread boost_fiber boost_context)
在 linux 平台上。 為什么我在 windows 平台上不需要它?
我記得 Linux 也可以自動鏈接庫。
我怎樣才能實現它?
提升文檔:
自動鏈接
大多數 Windows 編譯器和鏈接器都有所謂的“自動鏈接支持”,這就消除了第二個挑戰。 Boost 頭文件中的特殊代碼會檢測您的編譯器選項,並使用該信息將正確庫的名稱編碼到您的目標文件中; 鏈接器從您告訴它搜索的目錄中選擇具有該名稱的庫。
GCC 工具鏈(Cygwin 和 MinGW)是明顯的例外; GCC 用戶應參考Unix 變體操作系統的鏈接說明,以了解要使用的適當命令行選項。
請注意,已知自動鏈接功能有時會失敗(例如,當您的 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.