pavan
pavan

Reputation: 1

cmake : add_library cannot create target "cxx" because another target with the same name already exists

I'm using a project which has the following dependencies:

grpc

At the same time my project has benchmarks.

When I declare the following dependencies using FetchContent I get following error:

add_library cannot create target "benchmark" because another target
  with the same name already exists.  The existing target is an executable
  created in source directory

My CMakeLists.txt is:

cmake_minimum_required(VERSION 3.15)
project(dahj)

set(CMAKE_CXX_STANDARD 14)

include(FetchContent)

FetchContent_Declare(
        grpc
        GIT_REPOSITORY https://github.com/grpc/grpc.git
        GIT_TAG v1.17.2
)
FetchContent_MakeAvailable(grpc)

FetchContent_Declare(
        benchmark
        GIT_REPOSITORY https://github.com/google/benchmark.git
        GIT_TAG v1.5.0
)
FetchContent_MakeAvailable(benchmark)

add_executable(dahj main.cpp grpc++)

I know that I can use benchmark without fetching it but by just linking it. But if grpc decides to take off benchmark as a dependency it screws my build. Is there a better way to do this?

Upvotes: 0

Views: 6628

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65936

Call FetchContent_Declare and FetchContent_MakeAvailable for benchmark only when there is no "benchmark" target created yet:

if (NOT TARGET benchmark)
    FetchContent_Declare(
            benchmark
            GIT_REPOSITORY https://github.com/google/benchmark.git
            GIT_TAG v1.5.0
    )
    FetchContent_MakeAvailable(benchmark)
endif()

This will safely prevent benchmark project to be included twice.

See also that question: CMake : multiple subprojects using the same static library

Upvotes: 1

Related Questions