0

Complelety new to CMake. I am getting following error : add_library cannot create target "hello-pack" because another target with the same name already exists.

My directory structure are as such :

Directory structure

my app uses two libs : hello-pack and hello-world-pack.

hello-world-pack depends upon hello-pack too to deliver its functionality.

myapp2 CMakeLists.txt file content is as such :

cmake_minimum_required(VERSION 3.4.1)

project("myapp2" C)

add_subdirectory("hello-pack")
add_subdirectory("hello-world-pack")

add_executable("${PROJECT_NAME}" myapp2.c)
target_include_directories("${PROJECT_NAME}" 
    PRIVATE "hello-pack/include" 
    PRIVATE "hello-world-pack/include")
target_link_libraries("${PROJECT_NAME}" "hello-pack" "hello-world-pack")
target_link_directories("${PROJECT_NAME}" 
PRIVATE "hello-pack"
PRIVATE "hello-world-pack")

Here is the git repo for this code: https://github.com/anuragvohraec/myapp2.git

hello-pack prints out: hello!

hello-pack code

and hello world prints out: hello! world!

enter image description here

I wanted to simulate a situation where in my main app and a dependent library uses a common package for building.

Kevin
  • 16,549
  • 8
  • 60
  • 74
Anurag Vohra
  • 1,781
  • 12
  • 28
  • You already add the target `hello-pack` via the call to `add_subdirectory("hello-pack")` in your top-level CMake. There is no need to define this target again in the `hello-world-pack` directory, unless this is a different set of code. Why does this code seem to be duplicated in two places? – Kevin Nov 09 '19 at 06:07
  • @squareskittles Lets assume `hello-world-pack` is thri party library which too depends upon `hello-pack`. I know the reason for the error, but I am looking for the solution. If in a real project if two or more libraires have common depedencies, hw to get it resolved in CMake, is what I am looking for. – Anurag Vohra Nov 09 '19 at 08:03
  • This is downside of `add_subdirectory` approach for include 3d-party project: CMake files for that project may conflict with CMake files of the main project. In general, you cannot fix the problem without modifying CMake files. Alternative approaches - pre-building 3d-party project (and possible using of [find_package](https://cmake.org/cmake/help/v3.15/command/find_package.html) after that) or including the subproject via [ExternalProject_Add](https://cmake.org/cmake/help/v3.16/module/ExternalProject.html) - don't suffer from this problem. – Tsyvarev Nov 09 '19 at 08:37
  • There are several questions on Stack Overflow about this topic: https://stackoverflow.com/questions/24998342/cmp0002-error-when-compiling-different-subproject-with-same-target, https://stackoverflow.com/questions/42978414/how-to-handle-a-transitive-dependency-conflict-using-git-submodules-and-cmake, https://stackoverflow.com/questions/44691109/in-cmake-how-to-create-targets-with-identical-names. – Tsyvarev Nov 09 '19 at 08:39

0 Answers0