创建封装2个其他项目的可执行文件

时间:2016-09-05 09:32:40

标签: c++ eclipse cmake executable

我在Eclipse C ++中使用Windows。我的项目中有这个结构:

subProject A
   -> creates a static library (works fine)
subProject B encapsulating subproject A
   -> creates a static library (works fine)
subProject TestA
   -> creates an executable (works fine)
subProject TestB
    |dev
      |src
      | CmakeList.txt
    |CmakeList.txt
   -> creates an executable (doesn't work)

这是TestB可执行文件的dev目录中的 CmakeList.txt

set(${PROJECT_NAME}_INCLUDE_DIRS
    $(CMAKE_CURRENT_SOURCE_DIR}/src
    CACHE STRING "" FORCE)

include_directories(${${PROJECT_NAME}_INCLUDE_DIRS})

file(GLOB_RECURSE ${PROJECT_NAME}_HEADER_FILES FOLLOW_SYMLINKS
  ./*.hpp
  ./*.h)

file(GLOB_RECURSE ${PROJECT_NAME}_SORUCE_FILES FOLLOW_SYMLINKS
  ./*.cpp
  ./*.c)

set(${PROJECT_NAME}_FILES ${${PROJECT_NAME}_HEADER_FILES}
    ${${PROJECT_NAME}_SOURCE_FILES})

# Additional includes and link directories and dependencies
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../install/${CMAKE_BUILD_TYPE}/A/include)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../install/${CMAKE_BUILD_TYPE}/B/include)

if(${CMAKE_BUILD_TYPE} STREQUAL "Release")
set(${PROJECT_NAME}_EXTRA_LIBRARIES ${${PROJECT_NAME}_EXTRA_LIBRARIES}
                     A
                     B
                     pthread)
elseif(${CMAKE_BUILD_TYPE} STREQUAL "Debug")
set(${PROJECT_NAME}_EXTRA_LIBRARIES ${${PROJECT_NAME}_EXTRA_LIBRARIES}
                     A
                     B
                     pthread)
endif()

# Add a library to the project
link_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../install/${CMAKE_BUILD_TYPE}/A/lib)
link_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../install/${CMAKE_BUILD_TYPE}/B/lib)

add_executable(${PROJECT_NAME} ${${PROJECT_NAME}_FILES})

target_link_libraries(${PROJECT_NAME} ${${PROJECT_NAME}_EXTRA_LIBRARIES})

install(FILES ${${PROJECT_NAME}_HEADER_FILES}
     DESTINATION ${CMAKE_INSTALL_PREFIX}/include/
     PERSMISSIONS OWNER_READ GROUP_READ WORLD_READ)

install(TARGETS ${PROJECT_NAME}
     ARCHIVE DESTINATION lib
     LIBRARY DESTINATION lib
     RUNTIME DESTINATION bin)

在我的B子项目中,在文件中,我有:

#include "A.hpp"

...
A algo;
A.method(parameters)

当我构建我的TestB时,我在上面2行的 B项目中出现了这个奇怪的错误,这使我的构建失败:

undefined reference to A::A()
undefined reference to A::method(parameter)

当我评论这些行并重建 B项目 TestB项目时,它工作正常,我在B项目中有一个库,在TestB中有一个.exe

我不明白我的问题在哪里。

1 个答案:

答案 0 :(得分:1)

B取决于A,因此请将B的CMakeLists.txt中的依赖项添加到带有target_link_libraries的A中。即使它是一个静态库,并且在构建B时也不会有任何实际的链接,这无论如何都会提示CMake每次将B链接到可执行文件时,你也有将之后的链接到AA必须在链接命令行中B之后,以便在您链接到B时知道A所需的符号。有关详细信息,请参阅here

如果您正在寻找快速修复,只需更改:

set(${PROJECT_NAME}_EXTRA_LIBRARIES ${${PROJECT_NAME}_EXTRA_LIBRARIES}
                     A
                     B
                     pthread)

到这个

set(${PROJECT_NAME}_EXTRA_LIBRARIES ${${PROJECT_NAME}_EXTRA_LIBRARIES}
                     B
                     A
                     pthread)