[CMake] Testing an exe with gtest - possible?

cen imbacen at gmail.com
Sat Nov 23 12:24:43 EST 2019


Thanks, this pointed me in the right direction.

I ended up moving main() to it's own file so nothing depends on it, 
using a static add_library (project sources minus the main.cpp) and 
depend on that target from gtest exe project. Works like a charm.


I missed the discourse announcement, I'll use it in the future.


Best regards, cen


On 11/20/19 3:16 PM, Kyle Edwards wrote:
> On Wed, 2019-11-20 at 00:54 +0100, cen wrote:
>> Hi
>>
>> I have an existing c++ exe project which I want to test with gtest.
>> I
>> have not yet found an easy way to keep the project as is and test it
>> directly since gtest insists (obviously) to link against the code
>> being
>> tested. I found a smart answer on SO to link against object files
>> and
>> that works ok but it's messy and a lot of manual setup after cmake
>> project generation, probably impossible to automate in cmake.
>>
>> The other quick way is to change the VS project output to a static
>> lib.
>> That also works but is a manual step which again not sure can be
>> automated at all. And there is a bigger issue hidden in here.. I
>> can't
>> link to this lib due to dual main() entry point.
>>
>> So unless there is some smart workaround to keep project as an exe
>> and
>> get gtest to work, I guess the only remaining option is to separate
>> the
>> main() into a small bootstrap exe and then link against the rest of
>> the
>> program (which contains the actual testable logic) as a lib. Finally,
>> if
>> I understand correctly, using target_link_libraries will
>> automatically
>> set up the two projects as dependent and lib will always get built
>> before the main is run.
> Check out the $<TARGET_OBJECTS:...> generator expression. This will let
> you link directly against the object files built for the executable.
>
> This mailing list is deprecated. Please post further discussion to
> Discourse:
>
> https://discourse.cmake.org/c/code
>
> Kyle


More information about the CMake mailing list