How do I setup gTest, so that I can link aganist the library? I will code in vim, so I just want to install the libraries, unlike the XCode setup. Goal is to be able to link a project against the library by setting -lgtest as linker flag and optionally, if I did not write my own test mainroutine, the explicit -lgtest_main flag.
Before you start make sure your have read and understood
this note from Google! This tutorial makes using gtest easy, but may introduce nasty bugs.
1. Get the googletest framework
$ wget https://github.com/google/googletest/archive/release-1.8.0.zip
Or get it by hand. I guess I won't manitain this little How-to, so if you stumbled upon it and the links are outdated, feel free to edit it.
2. Unzip and build google test
$ unzip gtest-1.8.0.zip
$ cd gtest-1.8.0
$ ./configure
$ make
3. "Install" the headers and libs on your system.
$ sudo cp -a include/gtest /usr/include
$ sudo cp -a lib/.libs/* /usr/lib/
gTestframework is now ready to use. Just don't forget to link your project against the library by setting -lgtest as linker flag and optionally, if you did not write your own test mainroutine, the explicit -lgtest_main flag.
From here on you might want to go to Googles documentation about the framework to learn how it works. Happy coding!
It's adviced that you link statically. There's no secret. Being a bit offtopic, I use CMake in my projects, which I recommend, and here (https://github.com/oblitum/operations) I have setup a very basic skeleton project that links to gmock and gtest (it's also adviced by google that you use the same gtest from gmock, when you use gmock). In the external folder reside the external CMake files that actually import gtest and gmock through ExternalProject_Add. In the sample, I'm setting the URL as a file path in my system where gmock and gtest are downloaded, but, if you check CMake ExternalProject_Add docs you can see that download urls, online repository urls are also available, which can allow your build to download gtest and gmock, and cache it, automatically.
I think cmake is an easy way to setup and use gtest on OSX. It works without manually copying files. Unzip gooletest-release-1.8.0, then
cd googletest-release-1.8.0
# create a build directory
mkdir build
cd build
# build configuration
cmake .. -DBUILD_GTEST=ON -DBUILD_SHARED_LIBS=ON
# build it
make
# installation
sudo make install
Afterwards, you can easily incorporate gtest in your project with the cmake commands
# sets GTEST_INCLUDE_DIRS and GTEST_LIBRARIES
find_package( GTest REQUIRED )
# adds the gtest include directory
include_directories( ${GTEST_INCLUDE_DIRS} )
# links gtest
target_link_libraries( yourTestApp ${GTEST_LIBRARIES} )
Related
I'm pulling in Boost using CPM to build another dependency of my project.
CPMAddPackage(
NAME Boost
VERSION 1.77.0
GITHUB_REPOSITORY "boostorg/boost"
GIT_TAG "boost-1.77.0"
)
The issue I'm having is exposing the header files to my dependency. I dumped all of the cmake variables, and there are many variables like boost_accumulators_SOURCE_DIR, boost_algorithm_SOURCE_DIR, boost_any_SOURCE_DIR, boost_asio_SOURCE_DIR, etc. My dependency depends on many of these libraries, and it's really tedious to list them all as include directories:
target_include_directories(
nghttp2_asio
PRIVATE "${boost_system_SOURCE_DIR}/include"
PRIVATE "${boost_config_SOURCE_DIR}/include"
PRIVATE "${boost_asio_SOURCE_DIR}/include"
PRIVATE "${boost_throw_exception_SOURCE_DIR}/include"
PRIVATE "${boost_assert_SOURCE_DIR}/include"
PRIVATE "${BoostAlign_SOURCE_DIR}/include"
PRIVATE "${boost_date_time_SOURCE_DIR}/include"
)
Is there a better way to do this?
CPM is just a thin layer around FetchContent, which in turn downloads your dependency into your build folder and then attempts to add_subdirectory it, adding it to your main build.
I think this is a bad idea for a lot of reasons...
Boost is one of the most commonly packaged C++ libraries, period. Integrating your project into an existing environment (like a Linux distro, or another package manager like Conan or Vcpkg) is going to be difficult if not impossible (without patching, I mean) since it will surely want your project to use the curated build of Boost.
Adding any third party CMake code to your own build is signing up for headaches... have you noticed how hard it is to write correct CMake code? What if Boost clobbers your cache variables or defines targets that conflict with yours?
CMake has built-in and standard support for locating many versions of Boost, including the newer versions that provide first-party CMake config modules.
Boost now provides first-party CMake config modules.
I don't think any build using Boost should be any more complex than this:
cmake_minimum_required(VERSION 3.22)
project(boost-usage-example)
find_package(Boost 1.77 REQUIRED system date_time)
add_executable(nghttp2_asio main.cpp ...)
target_link_libraries(
nghttp2_asio
PRIVATE
Boost::boost # all header-only libs: config asio throw_exception assert align
Boost::date_time
Boost::system
)
See the documentation here: https://cmake.org/cmake/help/latest/module/FindBoost.html
You only list as components (after REQUIRED) the non-header-only libraries. Those are also the ones that require special addition via target_link_libraries. Link to Boost::boost to get all the header-only modules.
This will work no matter what package manager you're using.
If you want to use vcpkg, create a file called vcpkg.json in your project root with the following contents:
{
"name": "boost-usage-example",
"version-string": "0.1.0-dev",
"dependencies": [
"boost-system",
"boost-config",
"boost-asio",
"boost-throw-exception",
"boost-assert",
"boost-align",
"boost-date-time"
]
}
You can also depend on just boost and it will acquire all boost modules, not just the ones you need. Then acquire vcpkg:
$ git clone https://github.com/microsoft/vcpkg.git
$ ./vcpkg/bootstrap-vcpkg.sh
Then build with:
$ cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=$PWD/vcpkg/scripts/buildsystems/vcpkg.cmake -DCMAKE_BUILD_TYPE=Release
$ cmake --build build
Done!
Suppose on the other hand that you wanted to use Conan. No big deal, just install Conan in a pip virtual environment:
$ python3 -m venv venv
$ . venv/bin/activate
$ python3 -m pip install -U pip setuptools wheel
$ python3 -m pip install conan
Then create a conanfile.txt with the following contents:
[requires]
boost/1.77.0
[generators]
cmake_paths
Install the dependencies:
$ mkdir build && pushd build && conan install .. && popd
And then build, using Conan's generated toolchain file:
$ cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=$PWD/build/conan_paths.cmake -DCMAKE_BUILD_TYPE=Release
$ cmake --build build
In fact, you can provide both a vcpkg.json and a conanfile.txt and your users will be free to use either one or neither and rely on their system package manager or a package manager you don't know about. In any case it will just work and you free yourself of a mountain of maintenance burdens.
I have found this library https://github.com/embeddedmz/ftpclient-cpp on GitHub but how to install it on Linux(Ubuntu) is quite obscure.
You will need CMake to generate a makefile for the static library or
to build the tests/code coverage program. Also make sure you have
libcurl and Google Test installed.
You can follow this script
https://gist.github.com/fideloper/f72997d2e2c9fbe66459 to install
libcurl.
This tutorial will help you installing properly Google Test on Ubuntu:
https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/
The CMake script located in the tree will produce Makefiles for the
creation of the static library and for the unit tests program.
To create a debug static library and a test binary, change directory
to the one containing the first CMakeLists.txt and :
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE:STRING=Debug
make
It is not clear to me what "to the one containing the first CMakeLists.txt" refers to. Is it the one in the Gtest? The one in Curl? Or What?
After trying both (the Cmake in Gtest and Curl) I still get the error: "No such file or directory" while trying to #include "FTPClient.h" .
UPDATE:
Listing what I am doing:
I did git clone https://github.com/embeddedmz/ftpclient-cpp.git then made the build folder, navigate into it, I tried cmake .. -DCMAKE_BUILD_TYPE:STRING=Debug (this is the literal command I inserted) and I get
Cmake Error at CmakeLists.txt: 27 (add_subdirectory): add_subdirectory given source "TestFTP" which is not an existing directory
So what is wrong so far?
After you build the library, there will be a libftpclient.a generated in your build tree.
You can install it to your system as follows:
In this case, copy libftpclient.a to /usr/local/lib and the two header files in FTP to /usr/local/include.
You should then be able to include the header files by adding the -I/usr/local/include flag and link by adding -L/usr/local/lib -lftpclient.
I'm working on c++ project on a linux machine and it uses several boost libraries. I've installed them on my system using vcpkg and build it using the toolchain provided by vcpkg. My question is:
How do I define the dependencies so that they automatically install on a different system, if they were to build it?
Conan has a way of doing it by defining the dependencies in conanfile.txt. How do I do the same with vcpkg?
Edit1: I've found autovcpkg which does the job I'm looking to do but can the same be done natively inside cmakelists.txt or by vcpkg itself?
If you have vcpkg as a submodule for your project, define a manifest for the libraries you want vcpkg to build, and are using the vcpkg CMake toolchain - then you will get everything you want.
Adding vcpkg as a submodule means that your users don't need to install it themselves, the CMake toolchain will install it on your behalf. It also means that you can fix the package versions
Using a manifest file is how you programmatically tell vcpkg which packages to get and build during a CMake configuration phase
Using a CMake toolchain file is the only way to tie this into your project's build system
$ git clone .../my_project
$ cd ./my_project
$ git submodule update --init
$ mkdir ../build
$ cd ../build
$ cmake ../my_project
-- Running vcpkg install
-- Running vcpkg install - done
...
I've found autovcpkg which does the job I'm looking to do but can the same be done natively inside cmakelists.txt or by vcpkg itself?
You can write a vcpkg port for your library or executable by providing a CONTROL and portfile.cmake file. In the CONTROL file you define all the dependencies and possible features while the portfile contains the build instruction. You can use vcpkg create <myport> <url> <filename> to create the CONTROL and portfile.cmake from a template which can be customized to your needs.
Together with a port-overlay this port can also be used by others without being merged into vcpkg/master
I'm looking for successful example of Catch CatchLib integration with CMake test (Ctest) . as I understand this is additional cmake script which has to parse application ouput?
Did someone already written this? probably shared this?
==================================================
update (solution has been found) :
I've committed cmake script to CatchLib , for the integration Catch with CTest. this is a simplified version of Fraser99's cmake script here
Integrating Catch with CMake is rather simple, as it's a header-only library.
Here's a quick rundown of what you have to do:
You can either assume that the Catch sources are already installed on the build machine or use ExternalProject for fetching them as part of the build process.
In either case, you will end up with the Catch header files in some known directory on your build machine. I would recommend creating an interface target for making this information known to your test executables:
add_library(Catch INTERFACE)
target_include_directories(Catch INTERFACE ${YOUR_CATCH_INCLUDE_DIR})
That way, you can simply specify Catch as a dependency to target_link_libraries:
add_executable(my_test ${MY_TEST_SOURCES})
target_link_libraries(my_test PUBLIC Catch)
As usual with CMake, add_test takes care of introducing the tests to CTest:
enable_testing()
add_test(NAME MyAwesomeTest COMMAND my_test)
And that's it already. Run make test on the built project to run your tests.
I have a project on Github that does this if you need to see a complete working example.
Update for newer versions of Catch: If you've already upgraded to Catch2, that one comes with its own package config file so you can just integrate it calling find_package. This provides a smoother CMake integration overall and you don't have to start defining your own interface target. While the approach above will still work even with Catch2, I would recommend using find_package if your Catch version supports it already.
Install catch with:
$ git clone https://github.com/catchorg/Catch2 <catch_src_dir>
$ mkdir <catch_bin_dir>
$ cd <catch_bin_dir>
$ cmake -DBUILD_TESTING:BOOL=FALSE <catch_src_dir>
$ make
$ make install
Then do add the following to the CMakeLists.txt:
find_package(Catch2 REQUIRED)
target_link_libraries(tests Catch2::Catch2)
See here.
My need is simple. I have to compile and use googletest on windows using MinGW with msys. Has anyone some experience doing this?
Thanks for answers.
It took me some time but I figured it out. Here is the guide for anyone who face the same problem.
To be able to compile GoogleTest on Windows follow this instructions:
I assume you have MinGW with MSYS istalled.
Download and install CMake from the official site http://www.cmake.org/. Use the Win32 installer
version. Once you have completed the installation process copy executable files from
"xxx/CMake/bin" to "xxx/MinWG/bin".
Download and install Python from http://www.python.org/. Again, the Windows installer does the job
fine.
Once you have completed the installation process copy the "python.exe"
form python folder to
"xxx/MinWG/bin".
Download the latest stable GoogleTest from http://code.google.com/p/googletest/ and unpack it into some folder.
Run MSYS terminal and execute following commands.
cd xxx/gtest-x.x.x
cmake -G "MSYS Makefiles"
make
If you have compilation errors from pthread follow these instructions.
Copy the include folder "xxx/gtest-x.x.x/include" into your MinGW gcc include.
Copy the library files "xxx/gtest-x.x.x/*.a" into your MinGW gcc lib.
When you compile tests add "-lgtest" parameter to gcc.
EDIT
Commentators are right. The coping of executables worked for me but generaly it is not a good practice. Try to use a symbolic link instead.
To build libgtest.a without cmake/python, but only using mingw make, gtest now has a 'make' folder with a plain old makefile in it.
Make sure, mingw\bin is in the path (try running 'g++' or something).
Enter the gtest 'googletest\make' folder and run 'make'.
To test, run 'sample1_unittest' (gtest sample test output should appear).
To generate the library 'libgtest.a', run 'ar -rv libgtest.a gtest-all.o'
The library created is a full static library with no dll's generated.
That should be all.
By the way, this also works for building googlemock, just enter the googlemock folder instead of googletest, and follow the same procedure.
The question was asked in 2011 and answer with most votes is also answered the same year. So, a fresh answer would improve the question effectiveness.
Tools You need & I tested with:
Mingw64 8.0.2
GoogleTest GitHUb Source Code repo branch 1.10.0
CMake 3.20.4
and Windows10
Steps
Install the mingw64 by double clicking and chose the path which does
not have space between directory names e.g. "Program Files"
Open settings of the windows and then search environment variables
and oepn the dialog box to edit the Path environment variable
Add the mingw64/bin directory name in the Windows Path Environment
variable e.g. C:\Users[USERNAME]\mingw64\bin (replace [USERNAME]
with your username e.g. Michael or Lee etc)
Install CMake. It is double click install procedure. Make sure, its
bin directory path is added in the Path Environment Variable.
It would be installed in C:/Program Files/...
Download GoogleTest repo extract it and create a build directory
inside the extracted directory.
Execute the following commands
$ cd build
$ cmake .. -G "MinGW Makefiles"
$ mingw32-make.exe
Copy the four static libraries(*.a) from build directory
[ex: C:\Users[USERNAME]\sourcecodes\googletest-master\build\lib]
into lib of MingW64
[ex: C:\Users[USERNAME]\mingw64\x86_64-w64-mingw32\lib]
Go to the GoogleTest extracted repo, navigate to
[ex
C:\Users[USERNAME]\sourcecodes\googletest-master\googletest\include\gtest]
Copy that whole gtest directory and copy to the folder
C:\Users[USERNAME]\mingw64\lib\gcc\x86_64-w64-mingw32\8.1.0\include
You are done to go. You can build and link Googltest with your C++ project. I also paste a CMakelists.txt sample
cmake_minimum_required(VERSION 3.12)
project(ProjectName VERSION 1.0.0 LANGUAGES CXX)
include_directories(include)
set(SOURCES src/library.cpp include/library.h)
add_executable(libabc ${SOURCES})
#############
## Testing ##
#############
enable_testing()
find_library(GTest gtest)
add_executable (unitTest test/unit_test.cpp)
target_link_libraries (unitTest gtest gtest_main)
add_test(AllFactTest unitTest)
I hope it would work.
From the README of https://github.com/google/googletest/tree/master/googletest
:
When building Google Test as a standalone project, the typical workflow starts
with:
mkdir mybuild # Create a directory to hold the build output.
cd mybuild
cmake ${GTEST_DIR} # Generate native build scripts.
If you want to build Google Test's samples, you should replace the last command
with
cmake -Dgtest_build_samples=ON ${GTEST_DIR}
As alternative it is also possible to build googletest using the usual MSYS/Mingw make.
So here is my alternative way:
Make sure MSys/MingW is installed on your Windows and the PATH environment is set to it
Open a cmd window - you can set the PATH explicitly here as well
CD to the unzipped googletest directory
Call configure with sh (part of MSys): sh configure
Call make -> libgtest.a should be built. It is placed in your googletest-directory lib/.libs subdirectory
See README of googletest of how to integrate the libgtest.a to your system. Also see googletest primer in the googletest wiki of how to compile. Alternatively specify the library path for gcc -L<googleTestDir>/lib/.libs and add -lgtest to link with your test project executable.
When using ASSERT_DEATH macro to check for asserts in your tested code (meaning asserts in your lib or application, not in googletest), call SetErrorMode - example main:
#include <windows.h>
#include "gtest/gtest.h"
int main (int argc, char** argv)
{
// this prevents annoying error message boxes popping up
// when assert is called in your program code
SetErrorMode(SEM_NOGPFAULTERRORBOX);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
You don't need to copy the binaries as long as you have them in your path. Install python and CMake. Test them in your msys (MinGW console)
which cmake
which python
If you see the path, then you have the binaries. If not, add their path to your Environmental Variables>PATH or just update within msys (update installation paths if necessary)
export PATH=$PATH:/c/Program Files (x86)/CMake/bin/cmake.exe:/c/Python27/python.exe
Then you can build as suggested:
cd xxx/gtest-x.x.x
cmake -G "MSYS Makefiles"
make
Test if everything works:
cd make
make
./sample1_unittest.exe
With MSYS2, simply install the mingw-w64-x86_64-gtest package:
pacman -S mingw-w64-x86_64-gtest
Then compile tests with the flags -lgtest -lgtest_main.