简体   繁体   中英

Cannot link Boost library to C++14 app using CMake

I tried to search for same problem, but none of solutions doesn't work for me. I'm not available to compile it. I enclose cmake file and error code.

Cmake file:

cmake_minimum_required(VERSION 3.13.3)
project(proj)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

find_package(Threads)
find_package(Boost 1.68.0 REQUIRED COMPONENTS system filesystem thread)

include_directories(include ${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})

file(GLOB SOURCES source/*.cpp)

message(${Boost_LIBRARIES})
message(${Boost_LIBRARY_DIRS})
message(${Boost_INCLUDE_DIRS})

add_executable(proj ${SOURCES})
target_link_libraries(proj ${CMAKE_THREAD_LIBS_INIT} ${Boost_LIBRARIES})

Linker error:

Main.cpp:(.text._ZN5boost6system15system_categoryEv[_ZN5boost6system15system_categoryEv]+0x5): undefined reference to `boost::system::detail::system_category_instance'
CMakeFiles/proj.dir/source/Main.cpp.o: In function `boost::system::generic_category()':
Main.cpp:(.text._ZN5boost6system16generic_categoryEv[_ZN5boost6system16generic_categoryEv]+0x5): undefined reference to `boost::system::detail::generic_category_instance'
CMakeFiles/proj.dir/source/Server.cpp.o: In function `boost::asio::detail::socket_ops::close(int, unsigned char&, bool, boost::system::error_code&)':
Server.cpp:(.text._ZN5boost4asio6detail10socket_ops5closeEiRhbRNS_6system10error_codeE[_ZN5boost4asio6detail10socket_ops5closeEiRhbRNS_6system10error_codeE]+0x6b): undefined reference to `boost::system::detail::system_category_instance'
CMakeFiles/proj.dir/source/Server.cpp.o: In function `boost::asio::detail::socket_holder::~socket_holder()':

Methods:

void Server::startListening()
{
    while (true)
    {
        tcp::socket socket(m_io_service);

        m_acceptor.accept(socket);
        std::thread t(&Server::handleConnection, this, std::move(socket));
        t.detach();
    }
}

void Server::handleConnection(tcp::socket socket)
{
    ...
}

You should not use the directory based api, but the target based one.

As said by @Someprogrammerdude in the comments, you should find and use the boost librairies like that:

find_package(Boost 1.68.0 REQUIRED COMPONENTS system filesystem thread)

file(GLOB SOURCES source/*.cpp) # File GLOB is a bad CMake practice
add_executable(proj ${SOURCES})

target_link_libraries(proj PUBLIC
    boost::system
    boost::filesystem
    boost::thread
)

The target_link_libraries will add all the necessary include directories and linker flags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM