2
votes

I started playing around with CMake to create a project with Qt and test it with Google Test. At the moment, I succesfully found a way to compile and link all the required libraries. However, I couldn't find a way to link sources to test files with following project structure:

root
|
+-- CMakeLists.txt
+-- src
| |
| +-- CMakeLists.txt
| +-- MyClass.h
| +-- MyClass.cpp
|
+-- test
| |
| +-- CMakeLists.txt
| +-- MyClassTest.cpp
|
+-- lib
  |
  +-- gtest-1.6.0
    |
    +-- CMakeLists.txt

Root CMakeLists.txt contains add_subdirectory for gtest, src and test folders. I have succesfully compiled and run "Hello world" app and simple EXPECT_TRUE(true) test in order to check that each part compiles correctly. Unfortunately, I couldn't find a way to include my source file to tests. Is it possible with the following project structure?

PS I know that it is possible to compile my sources as a library and link it to tests, but I dislike that approach, since it is more appropriate for integration testing, rather then unit testing...

EDIT: Added class names to the tree

2
to your PS : it is also appropriate for unit testing. The only difference is the location of the compiled code. But that is your personal preferenceBЈовић

2 Answers

2
votes

You can add a global variable at the level of your root CMakeLists.txt:

set(ALL_SRCS CACHE INTERNAL "mydescription" FORCE)

In the first add_subdirectory(src), you can do:

set(ALL_SRCS ${ALL_SRCS} blabla.cpp CACHE INTERNAL "description")

And in the add_subdirectory(test), you continue with:

set(ALL_SRCS ${ALL_SRCS} bla_test.cpp CACHE INTERNAL "description")

You can then do, add_executable, or library or whatever, with all your sources files.

EDIT: add trick for global variables in CMake.

1
votes

In the root CMakeLists.txt you can add a include_directories(src) This will then also be used by the tests. Another thing you can do is in the test CMakeLists.txt add a include_directories(${<projectName>_SOURCE_DIR}) where projectName is the name specified using project(myproj) in the src/ CMakeLists.txt (if you specified a project in there of course. Also check the docs about project)