googletest icon indicating copy to clipboard operation
googletest copied to clipboard

Provide ALIAS targets to unify the usage

Open raghavchugh21 opened this issue 4 years ago • 1 comments

If googletest is made part of the dependent's build tree (via FetchContent), then usage is different compared to using it from an install location (via find_package).

Ever since FetchContent has been introduced, the example has been using googletest. See here.

Usage differences in code:

make googletest part of hte build tree

include(FetchContent) FetchContent_Declare(googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG master) FetchContent_MakeAvailable(googletest)

no ALIAS target, must use non-namespaced target instead

target_link_libraries(my_target PRIVATE gtest_main)

----

use googletest from an install location

find_package(GTest REQUIRED CONFIG)

the install(EXPORT) command namespaces the targets

target_link_libraries(my_target PRIVATE GTest::gtest_main) I see from another issue (#3040 (comment)), that due to CMake 3.19 deprecating <2.8.12 there are also plans to set that as the minimum version and conveniently 2.8.12 is also the version that introduced the ALIAS form for add_library.

raghavchugh21 avatar Mar 17 '21 16:03 raghavchugh21

If googletest is part of the build tree, you can link to GTest::gtest_main rather than gtest_main. This is different than CMake's finders, which want you to link to GTest::Main. Depending on the how the library is brought in, the alias name changes, which I would say is extremely confusing.

Here is my method which works with both cases.

find_package(GTest)
if(NOT GTest_FOUND)
    message("Fetching Gtest because it wasn't found")

    # Reference: https://google.github.io/googletest/quickstart-cmake.html
    include(FetchContent)
    FetchContent_Declare(
        googletest
        URL https://github.com/google/googletest/archive/refs/tags/release-1.12.1.zip
    )
    # For Windows: Prevent overriding the parent project's compiler/linker settings
    set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
    FetchContent_MakeAvailable(googletest)

    # A patch for this method where gtest doesn't instead has aliases of GTest::gtest_main
    add_library(GTest::Main ALIAS gtest_main)
endif()

target_link_libraries(my_target PRIVATE GTest::Main)

It's a hack, but it unifies the targets so that it won't download gtest if you already have it, and the consuming code can always link to the same thing.

RFRIEDM-Trimble avatar Jul 07 '22 03:07 RFRIEDM-Trimble