I'm new to cmake and I'm trying to create a CMakeLists.txt for compiling my test files.
I have 3 files: calc.cpp
, calc.hpp
, and calc_test.cpp
and I use the following command to compile my tests:
g++ -o calc_test calc_test.cpp calc.cpp -lgtest -lpthread
which generates a binary file (calc_test
) that I execute to run my tests.
Here's my calc.hpp
:
#ifndef CALC_HPP_
#define CALC_HPP_
int add(int op1, int op2);
int sub(int op1, int op2);
#endif
My calc.cpp
:
#include "calc.hpp"
int add(int op1, int op2) {
return op1 + op2;
}
int sub(int op1, int op2) {
return op1 - op2;
}
And my calc_test.cpp
:
#include <gtest/gtest.h>
#include "calc.hpp"
TEST(CalcTest, Add) {
ASSERT_EQ(2, add(1, 1));
ASSERT_EQ(5, add(3, 2));
ASSERT_EQ(10, add(7, 3));
}
TEST(CalcTest, Sub) {
ASSERT_EQ(3, sub(5, 2));
ASSERT_EQ(-10, sub(5, 15));
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Now I have created a CMakeLists.txt file to compile my test files and it generates Makefile successfully, but when I execute cmake --build .
it throws undefined reference
error.
Here's the content of my CMakeLists.txt
:
cmake_minimum_required(VERSION 3.10)
project(Google_Test)
add_library(TestModlue calc.cpp)
target_link_libraries(TestModlue -lgtest -lpthread)
add_executable(calc_test calc_test.cpp)
What am I doing wrong?