How to include external library (boost) into CLion C++ project with CMake? - c++

I have the following setup for C++ development:
OS X Yosemite
CLion 140.2310.6 (a cross-plattform C/C++-IDE by JetBrains using CMake as build system)
installed boost via brew install boost into /usr/local/Cellar/boost/
Now, my goal is to setup a simple project and include the boost library. I defined just one test.cpp file that looks like this:
#include <iostream>
#include <boost>
using namespace std;
int test() {
cout << "Hello, World!" << endl;
return 0;
}
My CMakeLists.txt file looks like this:
cmake_minimum_required(VERSION 2.8.4)
project(MyProject)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
include_directories("/usr/local/Cellar/boost/1.57.0/include/boost")
set(SOURCE_FILES main.cpp ./test.cpp)
add_executable(MyProject ${SOURCE_FILES})
When I build the project, I get the following error:
/Users/nburk/Documents/uni/master/master_thesis/MyProject/test.cpp:2:10:
fatal error: 'boost' file not found
make[3]: *** [CMakeFiles/MyProject.dir/test.cpp.o] Error 1
make[2]: *** [CMakeFiles/MyProject.dir/all] Error 2
make[1]: *** [CMakeFiles/MyProject.dir/rule] Error 2
make: *** [MyProject] Error 2
I played around with adjusting paths here and there and also using add_library and target_link_libraries, none of which made the project build successfully.
Can someone point into the right direction how to make sure I can include boosts functionality into my CLion C++ project?
Update:
Thanks to #Waxo's answer I used the following code in my CMakeLists.txt file which:
set(Boost_INCLUDE_DIR /usr/local/Cellar/boost/1.57.0)
set(Boost_LIBRARY_DIR /usr/local/Cellar/boost/1.57.0/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
I now got past the file not found-error, but instead I get the following:
CMake Error at /Applications/CLion
EAP.app/Contents/bin/cmake/share/cmake-3.1/Modules/FindBoost.cmake:685
(file):
file STRINGS file "/usr/local/Cellar/boost/1.57.0/boost/version.hpp" cannot be read.
Call Stack (most recent call first): CMakeLists.txt:11
(find_package)
Any ideas what I am still missing? The referred line (685) in FindBoost.cmake is:
file(STRINGS "${Boost_INCLUDE_DIR}/boost/version.hpp" _boost_VERSION_HPP_CONTENTS REGEX "#define BOOST_(LIB_)?VERSION ")

After spending the whole afternoon on the issue, I solved it myself. It was a rather stupid mistake and all the hints in #Waxo's answer were really helpful.
The reason why it wasn't working for me that I wrote #include <boost> within my test.cpp-file, which apparently is just wrong. Instead, you need to refer directly to the header files that you actually want to include, so you should rather write e.g. #include <boost/thread.hpp>.
After all, a short sequence of statements should be enough to successfully (and platform-independently) include boost into a CMake project:
find_package(Boost 1.57.0 COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(BoostTest main.cpp)
target_link_libraries(BoostTest ${Boost_LIBRARIES})
These lines are doing the magic here. For reference, here is a complete CMakeLists.txt file that I used for debugging in a separate command line project:
cmake_minimum_required(VERSION 2.8.4)
project(BoostTest)
message(STATUS "start running cmake...")
find_package(Boost 1.57.0 COMPONENTS system filesystem REQUIRED)
if(Boost_FOUND)
message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
message(STATUS "Boost_VERSION: ${Boost_VERSION}")
include_directories(${Boost_INCLUDE_DIRS})
endif()
add_executable(BoostTest main.cpp)
if(Boost_FOUND)
target_link_libraries(BoostTest ${Boost_LIBRARIES})
endif()

Try using CMake find_package(Boost)
src : http://www.cmake.org/cmake/help/v3.0/module/FindBoost.html
It works better and CMake is made for cross compilation and giving an absolute path is not good in a CMake project.
Edit:
Look at this one too : How to link C++ program with Boost using CMake
Because you don't link actually the boost library to your executable.
CMake with boost usually looks like that :
set(Boost_USE_STATIC_LIBS ON) # only find static libs
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.57.0 COMPONENTS date_time filesystem system ...)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(foo foo.cc)
target_link_libraries(foo ${Boost_LIBRARIES})
endif()

I couldn't find boost library using find_package() of clion. So my solution is download to the latest version boost from the following site:
https://sourceforge.net/projects/boost/files/boost/
After that, extract it and navigate to that folder in CMakeList.txt to include boost library.
include_directories("/path_to_external_library")
In my case, I use linux and so I put it under /usr/share/.
include_directories("/usr/share/boost_1_66_0")

Related

Installing boost on macos

I am trying to create a simple example using the boost library. I can successfully use CMake for the initial setup and it finds boost.
using the following code in CMakeLists.txt:
cmake_minimum_required(VERSION 3.18)
project(edge_detector)
find_package(Boost REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(edge_detector main.cpp)
target_include_directories(edge_detector PUBLIC ${Boost_INCLUDE_DIRS})
target_link_libraries(edge_detector ${Boost_LIBRARIES})
However when I try to build the project using make or CMake --build . boost is not found and I am met with this error:
I am not sure what I am missing, I would be grateful for any help
Your include directive must include a file not a directory.
Replace
#include <boost/algorithm/string>
with
#include <boost/algorithm/string.hpp>

Undefined reference errors in simple boost serialization

I have a minimal example of Boost serialization where I try to save an integer in a binary archive file
Here is main.cpp:
#include <iostream>
#include <fstream>
#include <boost/archive/binary_oarchive.hpp>
int main() {
int t = 0;
std::ofstream file("Test.bin");
boost::archive::binary_oarchive archive(file);
archive << t;
file.close();
return 0;
}
and here is the CMake file:
cmake_minimum_required(VERSION 3.15)
project(Test)
set(CMAKE_CXX_STANDARD 17)
find_package(Boost REQUIRED serialization)
add_executable(Test main.cpp)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(Test ${Boost_LIBRARIES})
endif()
When I try to run this program in CLion, I get a large list of undefined reference errors as shown here:
https://pastebin.com/8uX9MZFf
I have setup Boost using vcpkg package manager. I'm compiling using Mingw-w64. The CMake file loads without errors (only a warning that says "New Boost version may have incorrect or missing dependencies and imported targets," though I've heard this warning isn't of concern, as it just means the current version of CMake isn't aware of the newest version of Boost).
I've tried to look for solutions to this everywhere, but I can't seem to find anything that works here. Any help would be appreciated.
I'm using cmake 3.15.3, boost 1.73.0 and mingw-w64 6.0.
EDIT
I uninstalled and reinstalled Boost without using the package manager, and tried getting the serialization library again. In this context, CMake runs into errors saying it can't find Boost with serialization (Though it can find Boost alone). I set Boost_DEBUG to ON and looked at the output, and noticed the following things:
_boost_COMPILER = "-mgw81" (guessed)
CMake seems to guess that the compiler I used to compile boost was mgw81. I'm guessing it got the 8.1 from my gcc version, which is correct.
Searching for SERIALIZATION_LIBRARY_RELEASE: boost_serialization-mgw81-mt-x64-1_73;boost_serialization-mgw81-mt-x64;...
As a result of that compiler selection, it searches for a file with "-mgw81" in the name. The problem is that the library files generated when I built boost are named like so:
libboost_serialization-mgw8-mt-x64-1_73.a
This says "-mgw8" instead of "-mgw81". I don't know how to correct CMake or build boost in such a way that this conflict doesn't happen. I've tried rebuilding boost with toolset=gcc-8.1 instead of toolset=gcc, but I still get "-mgw8" in the library file names.
EDIT 2
I found the solution to the above issue. I've posted it below.
After realizing that the issue was what I mentioned in EDIT, I looked further into how that issue could be resolved, and I found out you can manually set the compiler that is used to search through the variable Boost_COMPILER.
I changed my CMake file to the following:
cmake_minimum_required(VERSION 3.15)
project(Test)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "C:/boost_1_73_0")
set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "C:/boost_1_73_0/libs")
set(Boost_DEBUG ON)
set(Boost_COMPILER -mgw8)
set(Boost_ARCHITECTURE -x64)
set(BOOST_ROOT C:/boost)
set(BOOST_INCLUDEDIR C:/boost/include/boost-1_73/boost)
set(BOOST_LIBRARYDIR C:/boost/lib)
set(BOOST_NO_SYSTEM_PATHS ON)
find_package(Boost REQUIRED serialization)
add_executable(Test main.cpp)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(Test ${Boost_LIBRARIES})
endif()
I believe the critical changes here were setting Boost_COMPILER and Boost_ARCHITECTURE. I realized Boost_ARCHITECTURE needed to be set from this question: Linking boost in CLion project.
With this CMake file, my main.cpp file from above ran properly.

Configuring Boost Library in CLion

It is my First time to use Boost lib, So of course I ran into problem:
First this is the CMAKELISTS.txt for my project:
===========================================
src/CMAKELISTS.txt:
===========================================
cmake_minimum_required(VERSION 3.15)
project(My_String)
set(CMAKE_CXX_STANDARD 17)
set(SOURCE_FILES MyString.cpp MyString.h main.cpp)
add_executable(My_String_src ${SOURCE_FILES})
===========================================
test/CMAKELISTS.txt:
===========================================
cmake_minimum_required(VERSION 3.15)
project(My_String)
set(CMAKE_CXX_STANDARD 17)
set(Boost_USE_STATIC_LIBS OFF)
set(SOURCE_FILES MyStringTest.cpp)
set(Boost_INCLUDE_DIR "C:\\Program Files\\Boost\\boost_1_71_0")
set(Boost_LIBRARIES "C:\\Program Files\\Boost\\boost_1_71_0")
find_package (Boost COMPONENTS unit_test_framework)
include_directories(${Boost_INCLUDE_DIR})
include_directories(../src)
add_executable (Boost_Tests_run ${SOURCE_FILES})
target_link_libraries (Boost_Tests_run ${Boost_LIBRARIES})
==============================================
top_level CMAKELISTS.txt for the whole project:
==============================================
cmake_minimum_required(VERSION 3.15)
project(My_String)
set(CMAKE_CXX_STANDARD 17)
add_subdirectory(src)
add_subdirectory(test)
Note: I have built the BOOST lib!enter code here
In MyStringTest.cpp I have:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE MyString_Test_Suite
#include <iostream>
#include "MyString.h"
#include "MyString.cpp"
#include <boost/test/unit_test.hpp>
The error that I get when I build the project:
[ 50%] Building CXX object test/CMakeFiles/Boost_Tests_run.dir/MyStringTest.cpp.obj
[100%] Linking CXX executable Boost_Tests_run.exe
C:\PROGRA~1\MINGW-~1\X86_64~1.0-P\mingw64\bin\ar.exe: unable to rename 'CMakeFiles\Boost_Tests_run.dir/objects.a'; reason: File exists
mingw32-make.exe[3]: *** [test\CMakeFiles\Boost_Tests_run.dir\build.make:86: test/Boost_Tests_run.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:141: test/CMakeFiles/Boost_Tests_run.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:148: test/CMakeFiles/Boost_Tests_run.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:130: Boost_Tests_run] Error 2
What is wrong with my configurations?
And what do i need to do to fix it?
The code is telling the linker to link this library ../src to your executable. This is an invalid operation, so remove this line:
target_link_libraries(Boost_Tests_run ../src)
The arguments to target_link_libraries() are reserved for targets and library names (including full paths to library files). The ../src argument does not fit either of those criteria, as it is simply a directory.
EDIT: Another potential issue is your Boost_LIBRARIES variable. Again, this should not be provided to target_link_libraries() if it just contains a directory path. It should instead contain the full path to the libraries, including the library names.
However, the modern FindBoost.cmake module provides a better approach. If you know the Boost components you want to use (e.g. filesystem), you should specify those components in your find_package() call:
find_package(Boost REQUIRED COMPONENTS filesystem)
Then, the find module will populate imported targets for you, and you can link to them like this instead:
target_link_libraries(Boost_Tests_run PUBLIC Boost::filesystem)
I suggest taking a look at some of the examples on this page.

Unable to find the requested Boost libraries boost_lboost_thread

I have been trying to run a Qt project in a CMake environment. The Qt project is using openCV and Boost dependencies. After successfully solving all compiling errors, I have been struggling with a Boost error.
As soon as I run CMake I get the following error:
Running "/usr/bin/cmake /home/labrat/Desktop/cam-proc '-GCodeBlocks - Unix Makefiles'" in /home/labrat/Desktop/cam-proc/build.
**CMake Error at /usr/share/cmake-3.5/Modules/FindBoost.cmake:1677 (message):**
Unable to find the requested Boost libraries.
Boost version: 1.58.0
Boost include path: /usr/include
Could not find the following Boost libraries:
boost_lboost_thread
Some (but not all) of the required Boost libraries were found. You may
need to install these additional Boost libraries. Alternatively, set
BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT
to the location of Boost.
**Call Stack (most recent call first):
src/libCam/CMakeLists.txt:7 (find_package)**
Boost version: 1.58.0
Found the following Boost libraries:
system
thread
filesystem
chrono
date_time
atomic
-- Configuring incomplete, errors occurred!
See also "/home/labrat/Desktop/cam-proc/build/CMakeFiles/CMakeOutput.log".
See also "/home/labrat/Desktop/cam-proc/build/CMakeFiles/CMakeError.log".
*** cmake process exited with exit code 1.
I analyzed the error given CMake Error at /usr/share/cmake-3.5/Modules/FindBoost.cmake:1677 (message): and opened the enormous FindBoost.cmake file and here is the part where the error is, according to the warning, located:
message(SEND_ERROR "Unable to find the requested Boost libraries.\n${Boost_ERROR_REASON}")
# Add pthread library on UNIX if thread component was found
_Boost_consider_adding_pthreads(Boost_LIBRARIES ${Boost_LIBRARIES})
else()
if(Boost_FIND_REQUIRED)
message(SEND_ERROR "Unable to find the requested Boost libraries.\n${Boost_ERROR_REASON}")
else()
if(NOT Boost_FIND_QUIETLY)
# we opt not to automatically output Boost_ERROR_REASON here as
# it could be quite lengthy and somewhat imposing in its requests
# Since Boost is not always a required dependency we'll leave this
# up to the end-user.
if(Boost_DEBUG OR Boost_DETAILED_FAILURE_MSG)
message(STATUS "Could NOT find Boost\n${Boost_ERROR_REASON}")
else()
message(STATUS "Could NOT find Boost")
endif()
endif()
endif()
endif()
Also since another part of the error message said Call Stack (most recent call first): src/libCam/CMakeLists.txt:7 (find_package) here I am attaching the CMakeLists.txt realted to the libcam project if that's helpful:
cmake_minimum_required (VERSION 2.8.12)
project(libCam)
find_package(Qt5Widgets REQUIRED)
find_package(OpenCV REQUIRED)
find_package(Boost COMPONENTS filesystem lboost_thread system REQUIRED)
find_package(Boost COMPONENTS system thread filesystem REQUIRED)
find_package(Qt5PrintSupport REQUIRED)
###
# make sure we use c++11
###
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )
INCLUDE_DIRECTORIES(${Qt5Widgets_INCLUDE_DIRS})
include_regular_expression("^([^b]|b[^o]|bo[^o]|boo[^s]|boos[^t]|boost[^/]).*$")
qt5_wrap_ui (UIS_HDRS qtinclude/imagemanager.ui qtinclude/stereomanager.ui qtinclude/stereolistwidget.ui qtinclude/connectionmenu.ui)
file(GLOB LIBCAM_SRCS
"include/*.h"
"include/*.cpp"
"include/*.hpp"
"qtinclude/*.h"
"qtinclude/*.cpp"
"qtinclude/*.hpp"
)
file(GLOB UI_RC
"qtinclude/qdarkstyle/*.qrc"
)
add_library(libCam SHARED ${LIBCAM_SRCS} ${UIS_HDRS} ${UI_RC})
target_include_directories (libCam PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} )
target_link_libraries (libCam Qt5::Widgets Qt5::PrintSupport Qt5::Core Qt5::Quick Qt5::Sql Qt5::XmlPatterns ${Boost_LIBRARIES} ${OpenCV_LIBS} )
I have been googling the error for the past two days looking for information and code to solve this problem, but I am running out of ideas. I tried to download boost 1.55 but it didn't work as the compiler only sees boost 1.58.
Any idea on how to shed light on this matter? Is there something I am leaving out?
The problem is the line
find_package(Boost COMPONENTS filesystem lboost_thread system REQUIRED)
which should be changed to
find_package(Boost COMPONENTS filesystem thread system REQUIRED)
or simply deleted, since it is then equivalent to the following line.

Cmake error when adding Boost library

I am trying to add Boost library to my project using the CMakeLists.txt in the follwing way:
set(BOOST_INCLUDEDIR "C:/boost_1_57_0")
set(BOOST_LIBRARYDIR "C:/boost_1_57_0/stage/lib")
find_package(Boost 1.57.0 COMPONENTS filesystem)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(test test.cpp)
target_link_libraries(test ${Boost_LIBRARIES})
However, I get the followng error: LINK : fatal error LNK1104: cannot open file 'libboost_filesystem-vc120-mt-1_57.lib'
libboost_filesystem-vc120-mt-1_57.lib is located in the stage/lib folder, so I don't know what is going on. I am compiling with Visual Studio 2013.
Any thoughts?
Try setting the Boost_USE_STATIC_LIBS and Boost_USE_MULTITHREADED CMake variables to ON before using find_package, i.e.:
set( Boost_USE_STATIC_LIBS ON )
set( Boost_USE_MULTITHREADED ON )
find_package( Boost 1.57.0 COMPONENTS filesystem )
I've come across this problem before and it seems as though, on multithreaded windows systems, the Boost bootstrap installer compiles multithreaded, static libraries by default. However, the CMake FindBoost script (which is used by find_package) searches for single-threaded, dynamic libraries by default.
Since you're using VS compiler I'll say you're working on Windows.
The error refers to the linker, which is failing to find boost libraries, as noticed.
Taking into account that the library exists in the boost path, my solution was to do a file(COPY) for the specific library, as a last resort.
if(WIN32)
set(BOOST_ROOT "C:/boost_1_57_0")
set(BOOST_LIBRARYDIR ${BOOST_ROOT}/stage/lib/)
endif()
find_package(Boost 1.57.0 EXACT REQUIRED system filesystem)
if(Boost_FOUND)
message(STATUS "found boost, Boost_LIBRARIES <" ${Boost_LIBRARIES} ">")
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
else()
message(STATUS "boost not found")
endif()
target_link_libraries(boost_test ${Boost_LIBRARIES})
file(COPY "${Boost_LIBRARY_DIRS}/boost_filesystem-vc120-mt-1_57.dll" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
You may add some log messages to the CMake in order to know the values returned in the
find_package.
Make sure the architecture (x64) matches.
$ cmake -A x64 ..
Use link_directories command before adding executables just like include_directories.
link_directories(${Boost_LIBRARY_DIRS})