Using boost.asio in CMake
Asked Answered
A

2

16

I am relatively new to CMake, and I'm trying use the boost asio library in my project.

I was able to get CMake to find other boost libraries such as smart_ptr and lexical_cast, but I get a linker error when I try to include boost/asio.hpp:

LINK : fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-1_40.lib'.  

I then tried to change my CMakeLists.txt from

find_package(Boost 1.40.0 REQUIRED)

to

find_package(Boost 1.40.0 REQUIRED COMPONENTS asio)

CMake then asks for Boost_ASIO_LIBRARY_DEBUG and Boost_ASIO_LIBRARY_RELEASE. Am I going about this the right way, and if so where should I point CMake to find these libraries. (I am using CMake 2.6 and boost 1.40.0)

Amylaceous answered 16/1, 2010 at 20:58 Comment(0)
M
25

According to the ASIO documentation:

The following libraries must be available in order to link programs that use Boost.Asio:

  • Boost.System for the boost::system::error_code and boost::system::system_error classes.
  • Boost.Regex (optional) if you use any of the read_until() or async_read_until() overloads that take a boost::regex parameter.
  • OpenSSL (optional) if you use Boost.Asio's SSL support.

If you look at your link error, you will see that it is looking for the Boost.System library. I would try changing your CMakLists.txt to read:

find_package(Boost 1.40.0 REQUIRED system)
Mesitylene answered 18/1, 2010 at 17:41 Comment(2)
And of course you also have to add target_link_libraries(YourExecutable ${Boost_LIBRARIES})Empiric
Boost:asio is a header only library, so we don't need to add it as component in find_package.Transaction
G
2

working example for modern versions:

cmake_minimum_required(VERSION 3.26)

#boost
project(p)

set(BOOST_INCLUDE_LIBRARIES thread filesystem system program_options asio date_time)
set(BOOST_ENABLE_CMAKE ON)

include(FetchContent)
FetchContent_Declare(
  Boost
  GIT_REPOSITORY https://github.com/boostorg/boost.git
  GIT_PROGRESS TRUE
  GIT_TAG boost-1.82.0
)
FetchContent_MakeAvailable(Boost)

#INCLUDE_DIRECTORIES(${BOOST_LIBRARY_INCLUDES})
#include_directories(asio INTERFACE ${boost_asio_SOURCE_DIR}/include)

# Add source to this project's executable.
add_executable (ComUdpProxy "ComUdpProxy.cpp" "ComUdpProxy.h" "Sender.h"  "Receiver.h" "Message.h")

#target_include_directories(ComUdpProxy PRIVATE ${BOOST_LIBRARY_INCLUDES})

target_link_libraries(ComUdpProxy
  PRIVATE 
  Boost::asio
  Boost::filesystem
  Boost::thread
  Boost::program_options
)

if (CMAKE_VERSION VERSION_GREATER 3.12)
  set_property(TARGET ComUdpProxy PROPERTY CXX_STANDARD 20)
endif()
Giavani answered 29/7, 2023 at 9:39 Comment(1)
this was the only way I could get asio to compile with boost with cmake...thanks!Amphiaster

© 2022 - 2024 — McMap. All rights reserved.