Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Boost.asio with cmake?

I want to static link boost.asio to my small project without external libs (having only single exe/bin file in result to distribute it). Boost.asio requires Boost.system and i start to drown trying to figure out how to compile this all. How to use Boost.asio with cmake?

like image 771
Fedcomp Avatar asked Dec 21 '22 08:12

Fedcomp


1 Answers

If I understand the actual question, it is fundamentally asking how to statically link against 3rd party libraries in CMake.

In my environment, I have installed Boost to /opt/boost.

The easiest way is to use FindBoost.cmake provided in a CMake installation:

set(BOOST_ROOT /opt/boost)
set(Boost_USE_STATIC_LIBS ON)
find_package(Boost COMPONENTS system)

include_directories(${Boost_INCLUDE_DIR})
add_executable(example example.cpp)
target_link_libraries(example ${Boost_LIBRARIES})

A variant that finds all Boost libraries and explicitly links against the system library:

set(BOOST_ROOT /opt/boost)
set(Boost_USE_STATIC_LIBS ON)
find_package(Boost REQUIRED)

include_directories(${Boost_INCLUDE_DIR})
add_executable(example example.cpp)
target_link_libraries(example ${Boost_SYSTEM_LIBRARY})

If you do not have a proper Boost installation, then there are two approaches to statically link against the libraries. The first approach creates an imported CMake target:

add_library(boost_system STATIC IMPORTED)
set_property(TARGET boost_system PROPERTY
  IMPORTED_LOCATION /opt/boost/lib/libboost_system.a 
)

include_directories(/opt/boost/include)
add_executable(example example.cpp)
target_link_libraries(example boost_system)

And the alternative is to explicitly list the library in target_link_libraries rather than the target:

include_directories(/opt/boost/include)
add_executable(example example.cpp)
target_link_libraries(example /opt/boost/lib/libboost_system.a)
like image 98
Tanner Sansbury Avatar answered Dec 24 '22 02:12

Tanner Sansbury