首页 > 解决方案 > CMake pybind11 无法创建目标,因为已经存在另一个同名目标,如何绕过?

问题描述

我有成功运行的代码。它的 CmakeLists.txt 是:

cmake_minimum_required(VERSION 3.15) project(rotapro3) set(CMAKE_CXX_STANDARD 14) add_executable(rotapro3 main.cpp)

我想在这个项目中使用 pybind,并按照说明添加以下行:

add_subdirectory(pybind)
pybind11_add_module(rotapro3 main.cpp)

它成功启动,但我收到一个错误:

 add_executable cannot create target "rotapro3" because another target with
  the same name already exists.  The existing target is a module library
  created in source directory "C:/Users/Alex/Dropbox/rotapro3".

我对 CMake 几乎一无所知。我怎样才能重写这些行以允许我使用add_executable

更新:

我还有另一个更复杂的案例:

    set(SOURCE_FILES
        unit_test/geometry/monomer_test.cpp
        unit_test/geometry/monomer_test.hpp
        unit_test/geometry/polymer_test.cpp
        unit_test/geometry/polymer_test.hpp
        unit_test/geometry/unit_box_test.cpp
        unit_test/geometry/unit_box_test.hpp
        unit_test/geometry/rect_shape_3d_test.cpp
        unit_test/geometry/rect_shape_3d_test.hpp
        src/general/guard.cpp
        src/general/guard.hpp
        src/general/fmt_enum.hpp
        src/general/string_format.cpp
        src/general/string_format.hpp
        src/geometry/monomer.cpp
        src/geometry/monomer.hpp
        src/geometry/polymer.cpp
        src/geometry/polymer.hpp
        src/geometry/unit_box.cpp
        src/geometry/unit_box.hpp
        src/geometry/rect_shape_3d.cpp
        src/geometry/rect_shape_3d.hpp
        )
include_directories(src/general)
include_directories(src/geometry)
include_directories(unit_test/general)
include_directories(unit_test/geometry)

add_executable(
        grapoli_lap ${SOURCE_FILES}
        unit_test/general/string_format_test.cpp
        unit_test/general/string_format_test.hpp
        unit_test/geometry/monomer_test.cpp
        unit_test/geometry/monomer_test.hpp
        unit_test/geometry/polymer_test.cpp
        unit_test/geometry/polymer_test.hpp
        unit_test/geometry/unit_box_test.cpp
        unit_test/geometry/unit_box_test.hpp
        unit_test/geometry/rect_shape_3d_test.cpp
        unit_test/geometry/rect_shape_3d_test.cpp
)

add_subdirectory(pybind11)
pybind11_add_module(grapoli_lap grapoli_lib.cpp)

target_link_libraries(grapoli_lap gtest gtest_main)

我遇到了同样的错误。

标签: cmakepybind11python-extensions

解决方案


在 CMake 中,您不能有两个具有相同名称的目标。因为pybind11_add_module()类似于add_library(),所以您应该使用此命令来创建库目标。您可以将此库命名为 target rotapro3。然后,您可以创建可执行目标,命名为其他名称(如rotapro3_exe):

cmake_minimum_required(VERSION 3.15)
project(rotapro3)
set(CMAKE_CXX_STANDARD 14)

add_subdirectory(pybind)
# Create the library rotapro3 target here.
pybind11_add_module(rotapro3 example.cpp)

# Create your executable target (with a different name).
add_executable(rotapro3_exe main.cpp)

推荐阅读