Как установить gtest ubuntu
Как настроить googleTest как общую библиотеку в Linux
Debian больше не предоставляет предварительно скомпилированных пакетов для gTest. Они предлагают вам интегрировать фреймворк в make-файл вашего проекта. Но я хочу, чтобы мой make-файл был чистым. Как мне настроить gTest, как предыдущие версии ( c++ linux unit-testing installation googletest
1. Получите фреймворк googletest.
2. Распаковать и собрать google test
3. «Установите» заголовки и библиотеки в вашу систему.
4. Обновите кеш компоновщика.
. и проверьте, знает ли GNU Linker библиотеки
Если результат выглядит так:
Отсюда вы можете перейти к документации Googles и старым документам о фреймворке, чтобы узнать, как он работает. Удачного кодирования!
Позвольте мне ответить на этот вопрос специально для пользователей Ubuntu. Сначала начните с установки пакета разработки gtest.
Обратите внимание, что этот пакет устанавливает только исходные файлы. Вы должны сами скомпилировать код, чтобы создать необходимые файлы библиотеки. Эти исходные файлы должны находиться в / usr / src / gtest. Перейдите в эту папку и используйте cmake для компиляции библиотеки:
Теперь, чтобы скомпилировать ваши программы, использующие gtest, вы должны связать его с:
У меня это отлично сработало на Ubuntu 14.04LTS.
Мне потребовалось время, чтобы понять это, потому что обычная команда make install была удалена, и я не использую cmake. Вот мой опыт, которым я хочу поделиться. На работе у меня нет доступа к корневой на Linux, так что я установил рамки тест Google под моей домашней директории:
Чтобы установить пакет в
/ usr / gtest / как общие библиотеки вместе с образцом сборки:
Чтобы проверить установку, используйте следующий test.c в качестве простого тестового примера:
Это избавляет вас от необходимости хранить исходный код gtest в вашем репозитории или устанавливать его где угодно. Он автоматически загружается и встраивается в ваше дерево сборки.
Обновление для Debian / Ubuntu
Итак, чтобы получить свои библиотеки из репозитория пакетов, вы можете сделать следующее:
Если вам нужна самая последняя версия Google Test, скачайте ее с github. После этого действия аналогичны:
Как видите, путь создания библиотек изменился. Имейте в виду, что новый путь может скоро стать действительным и для репозиториев пакетов.
Getting started with Google Test (GTest) on Ubuntu
by Erik Smistad · Published July 5, 2012 · Updated July 5, 2012
Google test is a framework for writing C++ unit tests. In this short post, I explain how to set it up in Ubuntu.
Start by installing the gtest development package:
sudo apt-get install libgtest-dev
Note that this package only install source files. You have to compile the code yourself to create the necessary library files. These source files should be located at /usr/src/gtest. Browse to this folder and use cmake to compile the library:
sudo apt-get install cmake # install cmake cd /usr/src/gtest sudo cmake CMakeLists.txt sudo make # copy or symlink libgtest.a and libgtest_main.a to your /usr/lib folder sudo cp *.a /usr/lib
Lets say we now want to test the following simple squareRoot function:
In the following code, we create two tests that test the function using a simple assertion. There exists many other assertion macros in the framework (see http://code.google.com/p/googletest/wiki/Primer#Assertions). The code contains a small main function that will run all of the tests automatically. Nice and simple!
The next step is to compile the code. I’ve set up a small CMakeLists.txt file below to compile the tests. This file locates the google test library and links it with the test application. Note that we also have to link to the pthread library or the application won’t compile.
Compile and run the tests:
Have fun testing! You can download all of the code above at my Github page: https://github.com/smistad/GTest
References
Fix NVIDIA driver 387 for Linux kernel 4.13+ on Ubuntu
by Erik Smistad · Published February 5, 2018 · Last modified February 12, 2018
Memory-mapped files using the boost library
by Erik Smistad · Published October 11, 2012
AMD OpenCL-OpenGL interoperability on Ubuntu Linux
by Erik Smistad · Published June 2, 2019
80 Responses
undefined reference to main…
how to write gtest in cpp if there is no return value from the function.
please show the sample for the same
Modern CMake suggests never using include_directories() as you are operating on the directory level. It’s much better operate just on the targets. See Youtube video (at:18:26) “C++Now 2017: Effective CMake” by Daniel Pfeifer
Hi, thanks for this quick guidance. However, I constantly meeting this same error:
tests.cpp:(.text+0xf8): undefined reference to `testing::Message::Message()’
anything I did wrong?
How to get html code coverage report for this tutorial…please help me
you can use “sudo make install” instead of copying the lib
How would this work on Linux Mint OS? I’ve been playing with it, and it doesn’t work the same.
Gtest is running in ubuntu 16.04 but not in ubuntu 18.04. Could you please tell what will be the issue.
[==========] Running 10 tests from 5 test cases.
[———-] Global test environment set-up.
[———-] 5 tests from AgentAppTest
[ RUN ] AgentAppTest.test_getInstance
When 1st test case encountered it will stop running.
Add gtest_main to the target_link_libraries so you can remove your main method in the test code. Like so:
Great! I didn’t know that, thanks for the tip
Very helpful guide and compensates for Google’s near universal-inability to provide decent docs or getting started guides for its open source projects. Thanks very much for this!
compilation errors have occurred while I build the FAST library on ubuntu.
/home/kerax/Desktop/FAST/src/source/CL/cl.hpp:4755:28: warning: ignoring attributes on template argument ‘cl_int
VECTOR_CLASS* binaryStatus = NULL,
^
In file included from /home/kerax/Desktop/FAST/src/source/CL/OpenCL.hpp:5:0,
from /home/kerax/Desktop/FAST/src/source/FAST/RuntimeMeasurementManager.hpp:6,
from /home/kerax/Desktop/FAST/src/source/FAST/ExecutionDevice.hpp:5,
from /home/kerax/Desktop/FAST/src/source/FAST/Data/DataObject.hpp:6,
from /home/kerax/Desktop/FAST/src/source/FAST/AffineTransformation.hpp:4,
from /home/kerax/Desktop/FAST/src/source/FAST/Visualization/View.hpp:5,
from /home/kerax/Desktop/FAST/src/source/FAST/Visualization/WindowWidget.hpp:13,
from /home/kerax/Desktop/FAST/src/source/FAST/Visualization/WindowWidget.cpp:1:
/home/kerax/Desktop/FAST/src/source/CL/cl.hpp:4755:28: warning: ignoring attributes on template argument ‘cl_int
VECTOR_CLASS* binaryStatus = NULL,
^
CMakeFiles/Makefile2:187: recipe for target ‘CMakeFiles/FAST.dir/all’ failed
make[1]: *** [CMakeFiles/FAST.dir/all] Error 2
Makefile:129: recipe for target ‘all’ failed
make: *** [all] Error 2
I just see two warnings, the actual error must be somewhere else in the output. If you need any help compiling FAST, please use the gitter chatrom instead: https://gitter.im/smistad/FAST
Crazy. The ubuntu package is not even compiled…
How to add the gtest libraries using g++?
If you want to write your own function, do hypotenuse rather than messing with a square root function that works!
That’s really helpful, thanks!
It works perfectly on Raspberry Pi 3 as well. Thank you so much 🙂
Hello,
If I separate the main test from the code, it does not execute the tests and says 0 test executed. Any idea?.
If you want to split the tests over multiple files you need to add the files to the line add_executable(runTests tests.cpp newFile.cpp) in CMakeLists.txt
very helpful, thanks
Very helpful and effective. Thanks a lot.
Thank You. I had struggled months ago trying to get going with GoogleTest.
Your example gave me reassurance that the install went correctly.
I used it on Centos 7
# s/apt-get/yum
Again thanks for helping some many others.
Hello Erik,
I don’t find the gmock after following your setup instructions here(by installing libgtest-dev). How can I add gmock seamlessly and run successfully? I tried but I am keeping getting some error. So I have to uninstall libgtest-dev.
Thanks
Great. Thanks a lot for this helpful info!!
Thanks…It helped me a lot.
Please some one help to resolve this.
correct the spelling of SquareRoot in tests.cpp code.
Haven’t tried google mock. Personally, I have moved on to using catch testing framework instead https://github.com/philsquared/Catch
Hi,
How to create link to the pthread library on ubuntu?
Regards
If you are compiling directly with gcc you can simply add -lpthread
Thanks! Solved my problem
Great guide for beginners, thank you!
Thanks Erik, helped me get started using gTest for my project.
Really clear, simple, short guide that did exactly what I wanted. Thank you!
Hi,
thanks for this guide. It is working now.
Thank you very much, this was very helpful!
At the last step, when I type cmake CMakeLists.txt, I get these errors:
CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:91 (MESSAGE):
Could NOT find GTest (missing: GTEST_INCLUDE_DIR)
Call Stack (most recent call first):
/usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:252 (_FPHSA_FAILURE_MESSAGE)
/usr/share/cmake-2.8/Modules/FindGTest.cmake:150 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
CMakeLists.txt:4 (find_package)
— Configuring incomplete, errors occurred!
Do you know how to solve this problem? Thanks.
I have solved this problem myself.
Previously I was downloading Google test from
https://code.google.com/p/googletest/
and got the error.
Now I am doing:
sudo apt-get install libgtest-dev
and exactly follow your steps. Now things work well.
my folder structure is as below :
-rw-r–r– 1 root root 4574 Sep 19 14:48 Makefile
-rw-r–r– 1 root root 499 Sep 19 14:22 tests.cpp
-rw-r–r– 1 root root 175 Sep 18 18:33 whattotest.cpp
I got some reference error while execute “make” command.
Error :
Linking CXX executable runTests
CMakeFiles/runTests.dir/tests.cpp.o: In function `testing::AssertionResult testing::internal::CmpHelperEQ(char const*, char const*, int const&, double const&)’:
tests.cpp:(.text._ZN7testing8internal11CmpHelperEQIidEENS_15AssertionResultEPKcS4_RKT_RKT0_[testing::AssertionResult testing::internal::CmpHelperEQ(char const*, char const*, int const&, double const&)]+0x9b): undefined reference to `testing::internal::EqFailure(char const*, char const*, testing::internal::String const&, testing::internal::String const&, bool)’
CMakeFiles/runTests.dir/tests.cpp.o: In function `testing::AssertionResult testing::internal::CmpHelperEQ(char const*, char const*, double const&, double const&)’:
tests.cpp:(.text._ZN7testing8internal11CmpHelperEQIddEENS_15AssertionResultEPKcS4_RKT_RKT0_[testing::AssertionResult testing::internal::CmpHelperEQ(char const*, char const*, double const&, double const&)]+0x99): undefined reference to `testing::internal::EqFailure(char const*, char const*, testing::internal::String const&, testing::internal::String const&, bool)’
collect2: ld returned 1 exit status
make[2]: *** [runTests] Error 1
make[1]: *** [CMakeFiles/runTests.dir/all] Error 2
make: *** [all] Error 2
Please help me in this.
Thanks,
Deepakgiri Aparnathi
I don’t know. I haven’t seen this error before.
How to set up googleTest as a shared library on Linux
Debian does not provide any precompiled packages for gTest anymore. They suggest you integrate the framework into your project’s makefile. But I want to keep my makefile clean. How do I set up gTest like the former versions ( Follow
12 Answers 12
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
Or get it by hand. I won’t maintain this little How-to, so if you stumbled upon it and the links are outdated, feel free to edit it.
2. Unpack and build google test
3. «Install» the headers and libs on your system.
This step might differ from distro to distro, so make sure you copy the headers and libs in the correct directory. I accomplished this by checking where Debians former gtest libs were located. But I’m sure there are better ways to do this. Note: make install is dangerous and not supported
4. Update the cache of the linker
. and check if the GNU Linker knows the libs
If the output looks like this:
then everything is fine.
From here on you might want to go to Googles documentation, and the old docs about the framework to learn how it works. Happy coding!
Let me answer this specifically for ubuntu users. First start by installing the gtest development package.
Note that this package only install source files. You have to compile the code yourself to create the necessary library files. These source files should be located at /usr/src/gtest. Browse to this folder and use cmake to compile the library:
Now to compile your programs that uses gtest, you have to link it with:
This worked perfectly for me on Ubuntu 14.04LTS.
It took me a while to figure out this because the normal «make install» has been removed and I don’t use cmake. Here is my experience to share. At work, I don’t have root access on Linux, so I installed the Google test framework under my home directory:
To install the package in
/usr/gtest/ as shared libraries, together with sample build as well:
To validate the installation, use the following test.c as a simple test example:
If you happen to be using CMake, you can use ExternalProject_Add as described here.
This avoids you having to keep gtest source code in your repository, or installing it anywhere. It is downloaded and built in your build tree automatically.
Update for Debian/Ubuntu
So, to get your libraries from the package repository, you can do the following:
If you want the most current version of Google Test, download it from github. After that, the steps are similar:
As you can see, the path where the libraries are created has changed. Keep in mind that the new path might be valid for the package repositories soon, too.
Русские Блоги
Введение и использование gtest
1. Что такое gtest
gtest являетсяКросс-платформенная(Liunx, Mac OS X, Windows, Cygwin, Windows CE и Symbian) Среда модульного тестирования C ++, выпущенная Google. gtest создан для написания тестов C ++ на разных платформах. Он предоставляет множество утверждений, фатальных и нефатальных суждений, параметризации, «тестов на смерть» и т. Д.
Поняв, что такое gtest, давайте изучим некоторые правила использования gtest!
1. ТЕСТ-макрос серии gtest
2>. Напишите первое утверждение как: ASSERT_FALSE (Abs (1) == 1)
Далее давайте создадим еще один тестовый пример, протестируем функции find () и size () класса Map и реализуем его, унаследовав test :: Test.
Макрос TEST в это время должен быть записан как TEST_F, а его первый параметр должен соответствовать имени класса,
Тестовый прибор TEST_F, тестовый прибор, набор тестов, который выполняет зарегистрированную функцию.
Код реализован следующим образом:
5. Простой пример gtest
Вышеупомянутые тестовые примеры тестируются в системе Linux, читатели должны установить gtest под Linux самостоятельно.
Обмен здесь закончен
Как установить Node.js и npm в Ubuntu 18.04
How to install Node.js and npm on Ubuntu 18.04
В этом руководстве мы покажем вам несколько различных способов установки Node.js и npm в Ubuntu 18.04. Те же инструкции применимы для любого дистрибутива на основе Ubuntu, включая Kubuntu, Linux Mint и Elementary OS.
Выберите вариант установки, подходящий для вашей среды. Чтобы узнать, какие версии Node.js поддерживаются, лучше всего проконсультироваться с документацией к приложению Node.js, которое вы используете.
Установка Node.js и npm из NodeSource
Чтобы установить Node.js и npm из репозитория NodeSource, выполните следующие действия:
Включите репозиторий NodeSource, выполнив следующую curl команду от имени пользователя с привилегиями sudo :
Команда добавит ключ подписи NodeSource в вашу систему, создаст файл репозитория источников apt, установит все необходимые пакеты и обновит кеш apt.
Если вам нужно установить другую версию, например 14.x, просто измените ее setup_12.x с помощью setup_14.x
После включения репозитория NodeSource установите Node.js и npm, набрав:
Nodejs пакет содержит как node и npm двоичные файлы.
Убедитесь, что Node.js и npm были успешно установлены, распечатав их версии:
Установка Node.js и npm с помощью NVM
Чтобы установить Node.js и npm с помощью NVM в вашей системе Ubuntu, выполните следующие действия:
1. Установка скрипта NVM (Node Version Manager)
Чтобы скачать и установить nvm скрипт, выполните:
Приведенная выше команда клонирует репозиторий NVM из Github в
Как видно из выходных данных, вы должны либо закрыть и снова открыть терминал, либо запустить команды, чтобы добавить путь к nvm сценарию в текущий сеанс оболочки. Вы можете делать все, что вам легче.
2. Установка Node.js и npm
Теперь, когда nvm установлен, вы можете установить последнюю доступную версию Node.js, набрав:
Результат должен выглядеть примерно так:
После завершения установки проверьте ее, распечатав версию Node.js:
Установим еще две версии, последнюю версию LTS и версию 8.10.0.
Чтобы вывести список установленных версий Node.js, введите:
Результат должен выглядеть примерно так:
Вы можете изменить текущую активную версию с помощью:
Если вы хотите изменить версию Node.js по умолчанию, используйте следующую команду:
Установите Node.js и npm из репозитория Ubuntu
Пакеты Node.js и npm доступны из репозиториев Ubuntu 18.04 по умолчанию.
На момент написания версия, включенная в репозитории Ubuntu, v8.10.0 является предыдущей версией TLS.
Для установки nodejs и npm запуска следующих команд:
Исполняемый файл Node.js из репозиториев Ubuntu назван, nodejs а не node из-за конфликта с другим пакетом.
Проверьте установку, выполнив:
Установить инструменты разработки
Чтобы иметь возможность компилировать и устанавливать собственные надстройки из npm, вам необходимо установить инструменты разработки.
Следующая команда установит все необходимые пакеты, включая компиляторы GCC :