I have a problem in understanding, how to efficiently introduce tests into a project. I have code, which is compiled to ProjectMain
executable, and I want to write tests for it (which compile to ProjectTest
executable). I would like to keep the tests separate from the code of the ProjectMain
, so the file structure is the following:
Project
include
foo_class.h
src
foo_class.cpp
main.cpp
test
include
src
foo_class_test.cpp
<"gtest_main" is used, so no "main.cpp" here>
CMakeLists.txt
CMakeLists.txt
How do I relate those two CMakeLists.txt
with each other, so that EVERY source file is compiled exactly once (when both ProjectMain
and ProjectTest
are built)? More precisely, what is the best way to let ProjectTest
know about foo_class
implementation?
I could add ProjectMain
's sources to ProjectTest
target, but that will basically mean recompilation of ProjectMain
. The better choice would be to split the latter into two parts: a library, which takes all the codebase of it, and a dummy executable with main
function only. Then ProjectTest
would just link to the library, but I'd prefer to build ProjectMain
into a single file (executable only).
So are there other alternatives? Or maybe I miss something? Maybe I can point somehow to CMake that ProjectTest
needs ProjectMain
's sources?
CodePudding user response:
Check out CMake's Object Libraries
I have personally never used them (I personally use the approach you mentioned with a library and an executable with just a main
function) but I think this is what you are looking for. Basically just compile source files into objects for linking later.
CodePudding user response:
in your cmakelists.txt you may define 2 executables:
add_executable(ProjectMain ${COMMON_SRC} ${ProjectMain_SRC} ) add_executable(ProjectTest ${COMMON_SRC} ${ProjectTest_SRC} )
with ProjectMain_SRC and ProjectTest_SRC to be defines before like this:
list(APPEND ProjectMain_SRC file_1 file_2 ...)
COMMON_SRC list contains files used by both of executables