Search code examples
makefilebuildcmakegoogletestexternal-project

Share ExternalProject between multiple projects in CMake


I would like to share an ExternalProject between different CMake projects. Imagine a structure like the following:

prj1
|- CMakeLists.txt
|- ...
prj2
|- CMakeLists.txt
|- ...
lib
|- ext
 |- gtest
  |- CMakeLists.txt
   |- googletest
    |_ actual_google_test_files

What I'm trying to obtain is telling CMakeLists.txt to use the gtest in lib/ext/gtest with ExternalProject, without re-building gtest everytime in place for each project.

Ideally, gtest gets built once in its folder and projects just use it. I tried using ExternalProject like explained here (http://kaizou.org/2014/11/gtest-cmake/) and including lib/ext/gtest/CMakeLists.txt in the projects, but gtest gets re-compiled for every user.


Solution

  • tldr: You should try to integrate google_test as "subproject" not as prebuilt and use a "meta" CMakeLists.txt...

    Please read https://crascit.com/2015/07/25/cmake-gtest/

    CMakeLists.txt.in:

    cmake_minimum_required(VERSION 2.8.2)
    project(googletest-download NONE)
    include(ExternalProject)
    ExternalProject_Add(googletest
    GIT_REPOSITORY https://github.com/google/googletest.git
    GIT_TAG master
    SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src"
    BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build"
    CONFIGURE_COMMAND ""
    BUILD_COMMAND ""
    INSTALL_COMMAND ""
    TEST_COMMAND ""
    )
    

    CMakeLists.txt:

    # Download and unpack googletest at configure time
    configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
    execute_process(COMMAND "${CMAKE_COMMAND}" -G "${CMAKE_GENERATOR}" .
    WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/googletest-download" )
    execute_process(COMMAND "${CMAKE_COMMAND}" --build .
    WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/googletest-download" )
    
    # Prevent GoogleTest from overriding our compiler/linker options
    # when building with Visual Studio
    set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
    
    # Add googletest directly to our build. This adds
    # the following targets: gtest, gtest_main, gmock
    # and gmock_main
    add_subdirectory("${CMAKE_BINARY_DIR}/googletest-src"
                 "${CMAKE_BINARY_DIR}/googletest-build")
    
    
    add_subdirectory(prj1)
    add_subdirectory(prj2)