我正在使用Clion,我已经在这篇帖子的帮助下设置了GoogleTest:
Setup Google test in CLion
最后让一切工作,除了我似乎无法从另一个文件调用任何函数,我不断得到"未定义的引用"错误。我不明白我错过了什么,所有文件似乎都正确链接。
CMakeLists.txt:
cmake_minimum_required(VERSION 3.6)
project(ComplexNumber)
add_subdirectory(src)
add_subdirectory(test)
src / CMakeLists.txt:
set(core_SRCS main.c ComplexNumber.c)
add_library(core ${core_SRCS})
add_executable(exe main.c)
target_link_libraries(exe core)
测试/的CMakeLists.txt:
cmake_minimum_required(VERSION 3.3)
project(Test)
project(Example)
include(CTest)
enable_testing()
#set(gtest_disable_pthreads on) #needed in MinGW
include(F:/Programming/C/AYED/ComplexNumber/.repo/DownloadProject/DownloadProject.cmake)
download_project(
PROJ googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG master
UPDATE_DISCONNECTED 1
)
add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR} EXCLUDE_FROM_ALL)
set(test_SRCS Test.cpp)
add_executable(runUnitTests ${test_SRCS})
target_link_libraries(runUnitTests gtest gmock core)
add_test(runUnitTests runUnitTests)
测试/ Test.cpp的:
#include <gtest/gtest.h>
#include "../src/ComplexNumber.h"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
TEST(ComplexNumberTest, positives){
ComplexNumber complexNumber1 = {5, -2};
ComplexNumber complexNumber2 = {7, 6};
ComplexNumber result = {12, 4};
ComplexNumber complexNumber3 = *sum(&complexNumber1, &complexNumber2);
EXPECT_EQ(complexNumber3.realNumber, result.realNumber);
}
错误消息:
CMakeFiles\runUnitTests.dir/objects.a(Test.cpp.obj): In function `ZN32ComplexNumberTest_positives_Test8TestBodyEv':
F:/Programming/C/AYED/ComplexNumber/test/Test.cpp:14: undefined reference to `sum(ComplexNumber*, ComplexNumber*)'
collect2.exe: error: ld returned 1 exit status
Test\CMakeFiles\runUnitTests.dir\build.make:99: recipe for target 'Test/runUnitTests.exe' failed
mingw32-make.exe[3]: *** [Test/runUnitTests.exe] Error 1
CMakeFiles\Makefile2:1106: recipe for target 'Test/CMakeFiles/runUnitTests.dir/all' failed
mingw32-make.exe[2]: *** [Test/CMakeFiles/runUnitTests.dir/all] Error 2
CMakeFiles\Makefile2:1118: recipe for target 'Test/CMakeFiles/runUnitTests.dir/rule' failed
mingw32-make.exe[1]: *** [Test/CMakeFiles/runUnitTests.dir/rule] Error 2
mingw32-make.exe: *** [runUnitTests] Error 2
Makefile:551: recipe for target 'runUnitTests' failed
答案 0 :(得分:0)
一些评论,我认为最终会帮助您解决问题
使用add_library
创建库时,最好精确确定这样的库类型:
add_library(core STATIC ${core_SRCS})
将main
源文件放在库中不是一个好主意。库不应该包含main
函数,否则会发生什么情况,例如在您的可执行文件中有两个main
函数时?因此,src/CMakeLists.txt
应为:
set(core_SRCS ComplexNumber.c)
add_library(core ${core_SRCS})
add_executable(exe main.c)
target_link_libraries(exe core)
确保sum(ComplexNumber*, ComplexNumber*)
中定义了ComplexNumber.c
。