如何使用 CMake 自动 link 提升库

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)

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;
}


我的图书馆文件夹:
根据上面的代码,我可以成功构建我的代码。但我讨厌代码:

link_libraries(pthread boost_thread boost_fiber boost_context)

在 linux 平台上。为什么我在 windows 平台上不需要它?
我记得 Linux 也可以自动 link 库。
我怎样才能实现它?

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()