c++cmakeboost-asiostatic-librariescmake-language

How to include asio boost in cmake project


I'm trying to include asio boost using CMakein my project but I'm getting this error. libraries linking is working in VS but I don't know how to link them in Cmake project.

Working Solution with VS:-

asio boost version: 1.24.0


VS ScreenShot

cmake_minimum_required(VERSION 3.10)
project(networking_examples)

#set(CMAKE_CXX_COMPILER D:/System/msys2/mingw64/bin/clang++)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Link Boost Asio library
target_include_directories(networking_examples PRIVATE "./asio-1.24.0/include")

add_executable(
  networking_examples
  ./src/index.cpp
)


CMake Project

I want to link ./asio-1.24.0/include with my project using CMAKE.

Error:

CMake Error at CMakeLists.txt:9 (target_include_directories):
  Cannot specify include directories for target "networking_examples" which
  is not built by this project.


-- Configuring incomplete, errors occurred!
See also "D:/Git Repo/c++/networking/cmake-build-debug/CMakeFiles/CMakeOutput.log".

Solution

  • When you use target_include_directories there is not target named networking_examples. You add that target after.

    Order matters, and just like in C++ symbols must be defined before they can be used.

    So you need to change to:

    add_executable(
      networking_examples
      ./src/index.cpp
    )
    
    # Asio library header directory
    target_include_directories(networking_examples PRIVATE "./asio-1.24.0/include")
    

    On another couple of notes: First you don't seem to be using Boost ASIO but rather the standalone header-only library.

    Secondly, you don't link with the library (it's a header-only library). You only tell the build-system where it can find the ASIO header files.