c++ 在CMakeLists.txt中出现CMake错误:14(目标链接库)

ubby3x7f  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(547)

我尝试将GTest项目添加到我的解决方案中。我有一个项目结构:my project structure我创建了Cryptograph和CryptographTests目录,然后在CryptographTests中创建了binTests和lib。我有一些CMakeLists.txt文件:

  • 加密文件/CMakeLists.txt:
cmake_minimum_required(VERSION 3.17)
project(Cryptograph)

set(CMAKE_CXX_STANDARD 17)

find_package(OpenSSL REQUIRED)

add_executable(Cryptograph main.cpp modulArithmetics.cpp modulArithmetics.h Speakers.cpp Speakers.h Crypt.cpp Crypt.h LongArithmetic.cpp LongArithmetic.h Signs.cpp Signs.h)
target_link_libraries(Cryptograph OpenSSL::SSL)
  • 加密测试/CMakeLists.txt:
project(CryptographTest)

add_subdirectory(lib/googletest)
add_subdirectory(binTests)
  • 密码编译测试/lib/CMakeLists.txt:
project(CryptographGTest)

add_subdirectory(lib)
  • 加密测试/bin测试/CMakeLists.txt:
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})

add_executable(runCommonTests FirstTest.cpp)

target_link_libraries(runCommonTests gtest gtest_main)
target_link_libraries(runCommonTests Cryptograph)
  • 和CMakeLists.txt文件:
cmake_minimum_required(VERSION 3.17)
project(CryptographGlobal)

set(CMAKE_CXX_STANDARD 17)

set (SOURCE_FILES main.cpp)
add_executable(cryptograph_samples ${SOURCE_FILES})

include_directories(Cryptograph)

add_subdirectory(Cryptograph)
add_subdirectory(CryptographTests)

target_link_libraries(cryptograph_samples Cryptograph)

在那之后,我得到了错误:

CMake Error at CryptographTests/binTests/CMakeLists.txt:6 (target_link_libraries):
  Target "Cryptograph" of type EXECUTABLE may not be linked into another
  target.  One may link only to INTERFACE, OBJECT, STATIC or SHARED
  libraries, or to executables with the ENABLE_EXPORTS property set.

CMake Error at CMakeLists.txt:14 (target_link_libraries):
  Target "Cryptograph" of type EXECUTABLE may not be linked into another
  target.  One may link only to INTERFACE, OBJECT, STATIC or SHARED
  libraries, or to executables with the ENABLE_EXPORTS property set.

在这个错误之前,我得到了错误lool像不能连接到Cryptograph.lib,但在我的变化错误也改变了。
我尝试将GTest项目添加到我解决方案中,但出现错误

gr8qqesn

gr8qqesn1#

你的直觉是你的测试可执行文件需要访问你的加密代码来测试它是正确的。但是,将一个可执行文件链接到另一个可执行文件是不可能的。
您可能希望将Cryptograph作为一个,这样它只编译一次,您的可执行文件(cryptograph_samplesrunCommonTests)就可以链接到它。
库也应该main()。否则它会在链接时与可执行文件的main()冲突。所以假设Cryptograph/main.cpp包含main()函数,它应该被排除。
因此,请替换以下行:

add_executable(Cryptograph main.cpp modulArithmetics.cpp ...)

与:

add_library(Cryptograph STATIC modulArithmetics.cpp ...) # no main.cpp

使用STATIC库是一种方法。您也可以使用SHAREDOBJECT库。请参阅下面的第一个参考链接,了解更多关于CMake库目标的一般信息。
如果需要执行Cryptograph/main.cpp,可以将其转换为链接到Cryptograph的可执行文件,如Cryptograph/CMakeLists.txt中所示:

add_executable(CryptographApp main.cpp)
target_link_libraries(CryptographApp Cryptograph)

资源

相关问题