#Adding Boost.Beast as Library

70 messages · Page 1 of 1 (latest)

molten solstice
#

I want to make an application with two interfaces. One should communicate via RestFull Api and the other one should communicate via Websockets.
I thought I might use Boost.Beast. However I struggle with setting it up. I downloaded boost_1_86_0. Now I don't know how to continue. Besides that I'm using cmake.

lethal lintelBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

molten solstice
#

Thank you, but I still don't know how to include Boost. I also don't know if I need to build it. And I also don't know where I should place the files in my project.
My project structure is simple and has a src folder with the main.cpp file.

lethal lintelBOT
#

@molten solstice Has your question been resolved? If so, type !solved :)

molten solstice
#

I have this CMakeLists.txt

cmake_minimum_required(VERSION 3.15)

# Set the project name and version
project(BoostTest VERSION 1.0 LANGUAGES CXX)

# Set the C++ standard to C++20
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# Include Conan-generated CMake files
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()

# Add the executable target
add_executable(BoostTest main.cpp)

# Link Boost libraries
target_link_libraries(BoostBeastExample ${CONAN_LIBS})

This is my conanfile.txt since I thought it might be easier to install the dependency via Conan

[requires]
boost/1.86.0
[generators]
CMakeDeps
CMakeToolchain
[layout]
cmake_layout

And I also have this test code. Tbh. I'm not sure if this code is actual correct. I just generated it and wanted to test it later on:

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio.hpp>
#include <iostream>

namespace beast = boost::beast;
namespace http = beast::http;
namespace asio = boost::asio;
using tcp = asio::ip::tcp;

int main()
{
    try
    {
        asio::io_context ioc;

        tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 8080));
        tcp::socket socket(ioc);

        std::cout << "Listening on http://127.0.0.1:8080\n";

        acceptor.accept(socket);

        beast::flat_buffer buffer;

        http::request<http::string_body> req;
        http::read(socket, buffer, req);

        std::cout << "Received request: " << req << "\n";

        http::response<http::string_body> res{
            http::status::ok, req.version()};
        res.set(http::field::server, "Boost.Beast");
        res.body() = "Hello, Beast!";
        res.prepare_payload();

        http::write(socket, res);
        socket.shutdown(tcp::socket::shutdown_send);
    }
    catch (std::exception const &e)
    {
        std::cerr << "Error: " << e.what() << "\n";
    }
}

Before I added the Conan part I was able to build it via VS Code CMake.

#

The last thing I did was using this command to build the libraries for boost with Conan:

conan install . --output-folder=build --build=missing
agile pilot
# molten solstice I have this CMakeLists.txt ``` cmake_minimum_required(VERSION 3.15) # Set the ...

so you already have conan. Qt Creator has conan integration builtin, if you don't mind switching IDE you can give it a try https://www.qt.io/download-qt-installer-oss . otherwise you'll have to kind of manually set up things

#

use this conanfile.py (and delete the conanfile.txt as they conflicts):

from conan import ConanFile
from conan.tools.cmake import CMakeToolchain

class Recipe(ConanFile):
    settings = "os", "compiler", "build_type", "arch"
    generators = "CMakeDeps"

    default_options = {
        "boost*:debug_level":1,
        "boost*:without_stacktrace":True,
    }

    def requirements(self):
        self.requires("boost/1.86.0")

    def generate(self):
        tc = CMakeToolchain(self, generator="Ninja")
        tc.user_presets_path = False
        tc.generate()

(you need tc.user_presets_path = False to disable presets generation, otherwise VS Code kind of gets confused and you have more issues)

#

boost stacktrace doesn't build with MinGW hence disabling it

#

In CMakeLists.txt, Add conan provider file to the top level includes, before the project() call:

list(APPEND CMAKE_PROJECT_TOP_LEVEL_INCLUDES
     ${CMAKE_SOURCE_DIR}/cmake-conan/conan_provider.cmake)

(this is not the best practice working with custom dependency provider, ideally you want to append this in command line, but this is the easiest way)

#

after that it's simple, you use

find_package(
  Boost CONFIG
  COMPONENTS <insert your required components here>
  REQUIRED)

target_link_libraries(
  BoostTest
  PRIVATE Boost::boost <and other boost dependencies if you need>)
molten solstice
#

ok, I added the submodule. Now, the directory is called cmake-conan inside of my project.

This is my current CMakeList.txt

cmake_minimum_required(VERSION 3.15)

list(APPEND CMAKE_PROJECT_TOP_LEVEL_INCLUDES
     ${CMAKE_SOURCE_DIR}/cmake-conan/conan_provider.cmake)

# Set the project name and version
project(BoostTest VERSION 1.0 LANGUAGES CXX)

# Set the C++ standard to C++20
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# Include Conan-generated CMake files
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()

# Add the executable target
add_executable(BoostTest main.cpp)

# Link Boost libraries
find_package(
  Boost CONFIG
  COMPONENTS <insert your required components here>
  REQUIRED)

target_link_libraries(
  BoostTest
  PRIVATE Boost::boost <and other boost dependencies if you need>)

Can you tell me how to continue since I'm a bit lost now? 🥲

agile pilot
#

remove the # Include Conan-generated CMake files parts, they're not needed. the only conan thing you need in CMakeLists.txt is that toplevel include thing

#

replace the insert your required components here with the components you actually need. i think you can remove it first and add later if you find things not working

#

if everything goes right, after reconfiguring the cmake project you should be able to #include boost headers

molten solstice
#

so i probably should remove just find_package and leave target_link_libraries there

agile pilot
#

you need find_package before target_link_libraries

#

that's unless you're using CMake's FetchContent. with conan and vcpkg it's almost always find_package(SomePackage CONFIG REQUIRED) and then linking it to your target

agile pilot
molten solstice
#
cmake_minimum_required(VERSION 3.15)

list(APPEND CMAKE_PROJECT_TOP_LEVEL_INCLUDES
     ${CMAKE_SOURCE_DIR}/cmake-conan/conan_provider.cmake)

# Set the project name and version
project(BoostTest VERSION 1.0 LANGUAGES CXX)

# Set the C++ standard to C++20
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# Add the executable target
add_executable(BoostTest main.cpp)

# Link Boost libraries
find_package(
  Boost CONFIG
  COMPONENTS
  REQUIRED)

target_link_libraries(
  BoostTest
  PRIVATE Boost::boost)
agile pilot
#

in find_package also remove the COMPONENTS since you won't be specifying any components right now

molten solstice
#

ok, I was wondering about it

molten solstice
agile pilot
#

vscode is cool. it's just not that beginner friendly when it comes to C++ because many things need to be manually set up

molten solstice
#

should I use now this command again? conan install . --output-folder=build --build=missing

agile pilot
#

don't use the conan command line, run cmake configure directly

molten solstice
#

ah i see

#

with default config ig

#

Configure failed. Would you like to attempt to configure with the CMake Debugger?

ewww, I got this error

agile pilot
#

copy the logs before this error

#

doesn't need to be full log, just the last 50 lines should be enough

molten solstice
#

[cmake] Does not match the generator used previously: Ninja
[cmake] Either remove the CMakeCache.txt file and CMakeFiles directory or choose a different binary directory.
[proc] The command: C:\msys64\mingw64\bin\cmake.EXE -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_C_COMPILER:FILEPATH=C:\msys64\mingw64\bin\gcc.exe -DCMAKE_CXX_COMPILER:FILEPATH=C:\msys64\mingw64\bin\g++.exe --no-warn-unused-cli -SC:/Users/Andre/Documents/gitProjects/BoostTest -Bc:/Users/Andre/Documents/gitProjects/BoostTest/build -G "Visual Studio 17 2022" exited with code: 1
[cpptools] The build configurations generated do not contain the active build configuration. Using "Debug" for CMAKE_BUILD_TYPE instead of "Release" to ensure that IntelliSense configurations can be found
[main] Configuring project: BoostTest
[proc] Executing command: C:\msys64\mingw64\bin\cmake.EXE -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_C_COMPILER:FILEPATH=C:\msys64\mingw64\bin\gcc.exe -DCMAKE_CXX_COMPILER:FILEPATH=C:\msys64\mingw64\bin\g++.exe --no-warn-unused-cli -SC:/Users/Andre/Documents/gitProjects/BoostTest -Bc:/Users/Andre/Documents/gitProjects/BoostTest/build -G "Visual Studio 17 2022"
[cmake] Not searching for unused variables given on the command line.
[cmake] CMake Error: Error: generator : Visual Studio 17 2022
[cmake] Does not match the generator used previously: Ninja
[cmake] Either remove the CMakeCache.txt file and CMakeFiles directory or choose a different binary directory.
[proc] The command: C:\msys64\mingw64\bin\cmake.EXE -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_C_COMPILER:FILEPATH=C:\msys64\mingw64\bin\gcc.exe -DCMAKE_CXX_COMPILER:FILEPATH=C:\msys64\mingw64\bin\g++.exe --no-warn-unused-cli -SC:/Users/Andre/Documents/gitProjects/BoostTest -Bc:/Users/Andre/Documents/gitProjects/BoostTest/build -G "Visual Studio 17 2022" exited with code: 1

agile pilot
#

remove the build folder and reconfigure

#

which is c:/Users/Andre/Documents/gitProjects/BoostTest/build according to the log

#

and CMakeCache.txt needs to be removed as well

molten solstice
#

Ah, well inside of the build is a second build directory which includes the boost library

agile pilot
#

for now just delete it, it's stored in other places as well

molten solstice
#

y, CMakeCache.txt is inside of the build directory

#

ok, i did

agile pilot
#

if you remove the build folder and reconfigure and still have the same error (which is likely), you need to change generator with a CMakeUserPresets.txt file.

#

Add a New Preset... -> Create from Compilers... -> find the MinGW and press Enter twice

molten solstice
#

for now it continues building

agile pilot
#

then open the CMakeUserPresets.txt and add a "generator": "Ninja" like this:

{
    "version": 4,
    "configurePresets": [
      {
        "name": "qt6-msvc",
        "displayName": "Qt6 (MSVC)",
        "description": "Configure with Qt6 (MSVC)",
        "binaryDir": "${sourceDir}/build/MSVC",
        "generator": "Ninja",
        "cacheVariables": {
          "CMAKE_PREFIX_PATH": "C:/Qt/6.8.0/msvc2022_64/lib/cmake",
          "CMAKE_C_COMPILER": "cl.exe",
          "CMAKE_CXX_COMPILER": "cl.exe"
        }
      }
    ],
    "buildPresets": [
        {
            "name": "qt6-msvc - Debug",
            "displayName": "Qt6 MSVC Debug",
            "configurePreset": "qt6-msvc",
            "configuration": "Debug"
        }
    ]
  }
#

ok, i'm just sending the tutorials in case you still have errors (because i'm going to take shower and will be afk for a while)

molten solstice
#

alright thanks man

agile pilot
#

the clangd integration is another story. you probably want to have clangd, otherwise auto completion won't understand the library and reports errors all the places

#

you create a .vscode folder, and inside there you create a settings.json file with content:

{
    "clangd.arguments": [
        "--compile-commands-dir=build"
    ]
}

the build should correspond to the relative path to the actual build folder

#

then you set set(CMAKE_EXPORT_COMPILE_COMMANDS ON) in your CMakeLists.txt so that it can generate a database file that teaches clangd how to find third-party libraries

#

then it should work, and yeah, you definitively need to install clangd VS Code extension (and disable IntelliSense since they conflicts)

#

goes afk

lethal lintelBOT
#

@molten solstice Has your question been resolved? If so, type !solved :)

molten solstice
# agile pilot remove the build folder and reconfigure

so reconfiguring worked pretty well. I also added the settings.json and clang. The red line under the imports of boost is gone now. I just still can't build it. I used vs code >CMake: Build for building and got this error in return:

C:\msys64\mingw64\bin\cmake.EXE --build  --config Debug --target all --
Error: could not load cache
build finished with error(s).

 *  The terminal process terminated with exit code: 1. 
 *  Terminal will be reused by tasks, press any key to close it. 
agile pilot
#

try removing just the CMakeCache.txt file and reconfigure, then try building. the could not load cache error can be caused by many weird reasons and usually goes away when you clean the cache (or the build folder) and reconfigure + rebuild

#

however if the issue persists, then there's something wrong with the setup, in that case post the full CMakeLists.txt and the screenshot of the filename list in the build folder

molten solstice
# agile pilot try removing just the `CMakeCache.txt` file and reconfigure, then try building....
[build] [2/2 100% :: 21.953] Linking CXX executable BoostTest.exe
[build] FAILED: BoostTest.exe 
[build] C:\WINDOWS\system32\cmd.exe /C "cd . && C:\msys64\mingw64\bin\g++.exe -g  CMakeFiles/BoostTest.dir/main.cpp.obj -o BoostTest.exe -Wl,--out-implib,libBoostTest.dll.a -Wl,--major-image-version,0,--minor-image-version,0 -LC:/Users/Andre/.conan2/p/b/boost5f6afc643b8e1/p/lib -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
[build] C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/14.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: CMakeFiles/BoostTest.dir/main.cpp.obj: in function `boost::asio::detail::winsock_init_base::startup(boost::asio::detail::winsock_init_base::data&, unsigned char, unsigned char)':
[build] C:/Users/Andre/.conan2/p/b/boost5f6afc643b8e1/p/include/boost/asio/detail/impl/winsock_init.ipp:39:(.text$_ZN5boost4asio6detail17winsock_init_base7startupERNS2_4dataEhh[_ZN5boost4asio6detail17winsock_init_base7startupERNS2_4dataEhh]+0x74): undefined reference to `__imp_WSAStartup'
[build] C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/14.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: CMakeFiles/BoostTest.dir/main.cpp.obj: in function `boost::asio::detail::winsock_init_base::cleanup(boost::asio::detail::winsock_init_base::data&)':
[build] C:/Users/Andre/.conan2/p/b/boost5f6afc643b8e1/p/include/boost/asio/detail/impl/winsock_init.ipp:56:(.text$_ZN5boost4asio6detail17winsock_init_base7cleanupERNS2_4dataE[_ZN5boost4asio6detail17winsock_init_base7cleanupERNS2_4dataE]+0x35): undefined reference to `__imp_WSACleanup'
[build] collect2.exe: error: ld returned 1 exit status
[build] ninja: build stopped: subcommand failed.
[proc] The command: C:\msys64\mingw64\bin\cmake.EXE --build c:/Users/Andre/Documents/gitProjects/BoostTest/build --config Debug --target all -- exited with code: 1
[driver] Build completed: 00:00:49.436
[build] Build finished with exit code 1
#
cmake_minimum_required(VERSION 3.15...3.21)

list(APPEND CMAKE_PROJECT_TOP_LEVEL_INCLUDES
     ${CMAKE_SOURCE_DIR}/cmake-conan/conan_provider.cmake)

# Set the project name and version
project(BoostTest VERSION 1.0 LANGUAGES CXX)

# Set the C++ standard to C++20
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Add the executable target
add_executable(BoostTest main.cpp)

# Link Boost libraries
find_package(
  Boost CONFIG
  REQUIRED)

target_link_libraries(
  BoostTest
  PRIVATE Boost::boost)
agile pilot
#

(and remember to actually switch to the new preset after creating the preset)

#

and the settings.json needs to be updated to point to the new build folder if it's different so that clangd can still find the compile option database, i remember vscode defaults to out/XXX for new preset

#

if it doesn't build even after creating new preset with ninja, then you have to fallback to this workaround:

if(MINGW)
 target_link_libraries(BoostTest PRIVATE ws2_32)
endif()

the error is hinted in the log output:

undefined reference to `__imp_WSACleanup'

it's a symbol that points to https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsacleanup. normally they should be linked when buidling with MinGW.

agile pilot
molten solstice
#

@agile pilot
So I just deleted the build folder again and added this to the CMakeList.txt

  PRIVATE Boost::boost
          ws2_32

I didn't need to add the presets in the end. For me it is now working. Thanks a lot :)

lethal lintelBOT
#

@molten solstice

It looks like you may have code formatting errors in your message

Note: Make sure to use back-ticks (`) and not quotes (')

Markup

```cpp
int main() {}
```

Result
int main() {}
molten solstice
#

!solved