我正在学习CMake,但不幸的是,大多数例子要么太简单,太复杂,要么文件夹结构与我设计的不同。
我得到一个错误,但首先我将解释文件夹结构(请做批判):
MyProject
bin
build
src
ComponentA
ObjectA.cpp
CMakeLists.txt
ComponentB
ObjectB.cpp
CMakeLists.txt
CMakeLists.txt
main.cpp
CMakeLists.txt
我希望能够使用它们的绝对路径包含一些文件,例如main.cpp
可能看起来像这样:
#include <ComponentB/ObjectB.h>
int main()
{
ComponentB cb(1, 2, 3);
}
,但在源文件中,我想包括它的头使用相对路径:
#include <ComponentB.h>
ComponentB::ComponentB(int a, int b, int c) : _ca(a, b){}
(如果这导致问题,我可以包括使用绝对路径)
我的CMakeLists文件看起来像:
MyProject/CMakeLists.txt
:
cmake_minimum_required(VERSION 3.9.1)
project(MyProject)
add_subdirectory(src)
MyProject/src/CMakeLists.txt
:
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_ROOT_DIR}/bin)
add_executable(MyProject main.cpp)
add_subdirectory(ComponentA)
add_subdirectory(ComponentB)
MyProject/src/ComponentA/CMakeLists.txt
:
target_sources(MyProject PUBLIC ComponentA.cpp)
MyProject/src/ComponentB/CMakeLists.txt
:
target_sources(MyProject PUBLIC ComponentB.cpp)
target_include_directories(MyProject PUBLIC ComponentA)
但是当我这样做的时候:
cd build
cmake ..
我得到这个错误:
CMake Error at src/ComponentA/CMakeLists.txt:2 (target_sources):
Cannot specify sources for target "MyProject" which is not built by
this project.
CMake Error at src/ComponentB/CMakeLists.txt:2 (target_sources):
Cannot specify sources for target "MyProject" which is not built by
this project.
CMake Error at src/ComponentB/CMakeLists.txt:3 (target_include_directories):
Cannot specify include directories for target "MyProject" which is not
built by this project.
在CMake 3.13中增加了target_sources
通过相对路径将源文件添加到不同目录下的目标的能力。因为您指定的最小版本是3.9.1,所以这根本行不通。
所讨论的政策是CMP0076,文件如下:
3.13新版功能。
target_sources()
命令将相对路径转换为绝对路径。在CMake 3.13及以上版本中,
target_sources()
命令现在在以下情况下将源文件的相对路径转换为绝对路径:
- 源文件添加到目标的
INTERFACE_SOURCES
属性。- 目标的
SOURCE_DIR
属性与CMAKE_CURRENT_SOURCE_DIR
不同。
这是适用于这里的第二个要点。
你真的应该用一个新版本的CMake。 任何比最新版本(3.23)落后几个版本的东西都是明显的受虐狂。