我试图链接到我使用CMake构建的静态库,并具有一个子目录结构。看起来像这样(->
代表目录):
Root
| - CMakeLists.txt
| -> First
| | - CMakeLists.txt
| | -> Object
| | | - object.cpp object.hpp
| |
| -> Second
| | - CMakeLists.txt
| | - secondObject.hpp secondObject.cpp
| |
| -> Third
| | - CMakeLists.txt
| | - thirdObject.hpp thirdObject.cpp
| |
| -> Main
| - CMakeLists.txt
| - main.cpp
在Root的cmake文件中:
cmake_minimum_required(VERSION 3.0)
project(Main)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
include_directories(First)
include_directories(Second)
include_directories(Third)
add_subdirectory(First)
add_subdirectory(Second)
add_subdirectory(Third)
add_subdirectory(Main)
在First的cmake文件中:
project(First)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
add_library(First STATIC Object/object.cpp Object/object.hpp)
add_dependencies(First Second Third)
target_link_libraries( First Second Third)
第二个和第三个相似,但是第二个仅取决于第三个,而第三个则完全不依赖任何东西。当我尝试将其与Main的cmake文件链接时,就会出现问题:
project(Main)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(Main First Second Third)
add_executable(Main main.cpp)
target_link_libraries(Main First Second Third)
当我从构建文件夹运行cmake ..
时,它会经历得很开心,并且不会抱怨。但是,当我在GUI中点击make或Generate for Windows时,我会抱怨object.hpp: No such file or directory
。我将此包含在main.cpp
中。很明显,我可以将其更改为#include <Object/object.hpp>
,但是我觉得这违反了链接到库的目的。 (也许这是错误的想法)。
我还遇到了类似的问题,在类似这样的其他结构中,在object.cpp
这样的文件中,即使#include "Object/object.hpp"
与object.hpp
。
如何正确地将Project Main链接到Project First,这样我就不必object.cpp
?还是这是唯一的方法?还是我走错路了?
答案 0 :(得分:0)
对我来说,CMakeLists.txt
的以下解决方案是可行的。我还认为您只需在顶级目录中调用一次add_project
。
添加额外的依赖项似乎是多余的,因为CMake用target_link_libraries
指出了这一点。我能够运行CMake并构建项目,但是除main.cpp
之外的文件都是空的。
这是我的CMakeLists.txt
First / CMakeLists.txt
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
add_library(First STATIC Object/object.cpp Object/object.hpp)
target_link_libraries( First Second Third)
Second / CMakeLists.txt
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
add_library(Second STATIC secondObject.cpp secondObject.hpp)
target_link_libraries( Second Third)
第三/CMakeLists.txt
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
add_library(Third STATIC thirdObject.cpp thirdObject.hpp)
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(Main)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
include_directories(First)
include_directories(Second)
include_directories(Third)
add_subdirectory(First)
add_subdirectory(Second)
add_subdirectory(Third)
add_subdirectory(Main)