How to include two different versions of the same dependency in a CMake project?
Asked Answered
H

1

6

I have ExternalProject in both versions 1.2 and 2.2 present in my system. ExternalProject is a CMake project and CMake finds the both versions without trouble when I ask for them. Command find_package(ExternalProject 1.2 EXACT) finds version 1.2 and find_package(ExternalProject 2.2 EXACT) finds version 2.2.

Versions 1 and 2 are not compatible with each other. The APIs are completely different.

I have a CMake project, MyProject, which has two targets, targetOne and targetTwo. TargetOne uses ExternalProject 1.2 and TargetTwo uses ExternalProject 2.2.

The below code does not do what I want. The same external dependency is not looked up twice. The compilation of TargetTwo fails. Does CMake support this scenario in any way? (except by renaming the ExternalProject version 2 and compiling it in a different location).

project(MyProject)

find_package(ExternalProject 1.2 EXACT)
add_executable(targetOne target_one.c)
target_link_libraries(targetOne ExternalProject::externalProject)

find_package(ExternalProject 2.2 EXACT)
add_executable(targetTwo target_two.c)
target_link_libraries(targetTwo ExternalProject::externalProject)
Hilaire answered 10/10, 2019 at 6:14 Comment(0)
D
7

You can't mix targets with the same names in the same CMakeLists.txt. Use different CMakeLists.txt - one for each executable target. Use add_subdirectory for this.

  • project ./CMakeLists.txt:
project(MyProject)
add_subdirectory(folder_one)
add_subdirectory(folder_two)
  • ./folder_one/CMakeLists.txt:
find_package(ExternalProject 1.2 EXACT)
add_executable(targetOne target_one.c)
target_link_libraries(targetOne ExternalProject::externalProject)
  • ./folder_two/CMakeLists.txt:
find_package(ExternalProject 2.2 EXACT)
add_executable(targetTwo target_two.c)
target_link_libraries(targetTwo ExternalProject::externalProject)

Also, for scope changing you can use the function

Dispread answered 11/10, 2019 at 7:26 Comment(1)
This works. Though it must be noted that CMakeCache.txt only contains one ExternalProject_DIR:PATH, the last found, i.e. for version 2.2 in this case. This probably has no practical meaning if the projects are found with Find*.cmake file or via CMake package cache, ~/.cmake/packages. If the package location is specified on the command line, e.g. -D ExternalProject_ROOT=<dir>, then this approach will not work.Hilaire

© 2022 - 2024 — McMap. All rights reserved.