Search code examples
c++boostboost-asioasio

boost::asio::co_spawn is undefined in MSVC


I am attempting to create a TCP server using boost.asio and following the examples you use co_spawn to start the listener function in a new thread.

When I try to use boost::asio::co_spawn Microsoft Visual Studios tells me it is undefined, I have included all files the boost example does.

TcpServer.h

#include <iostream>
#include <string>

#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/coroutine.hpp>

using namespace boost::asio;

class TcpServer
{
public:
    TcpServer(int port);
    ~TcpServer();
private:

};

TcpServer.cpp

#include "TcpServer.h"


/*
    Create a TcpServer on a given port
*/
TcpServer::TcpServer(int port)
{
    io_context ioCtx(1);

    /* E0020    identifier "co_spawn" is undefined  */
    co_spawn();
}


TcpServer::~TcpServer()
{
}

The above code tells me that co_spawn is undefined, I have searched other name spaces and checked for alternative functions and there is none. I thought maybe it was outdated documentation but the boost.asio reference for version 1.70.1 still lists co_spawn as a free function. See here

I am using Boost: 1.70.1 Microsoft Visual Studio 2017: v15.9.7


Solution

  • boost.asio has preprocessor code to detect the capabilities of the compiler and only turn on coroutine support if the compiler supports it.

    For MSVC, I think you will need to add the compiler flag /await to the compiler command line option list.

    reference: https://learn.microsoft.com/en-us/cpp/build/reference/await-enable-coroutine-support?view=vs-2019