用自定义源和包含目录构建cmake项目时出错

56lgkhnf  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(75)

我的项目工作正常,如果所有的.cpp.h文件都在根目录.但只要我使用自定义srcinclude目录分别为.cpp.h和改变CMakeLists.txt文件,CMake构建显示错误.
项目结构:

CMakeLists.txt
include
    mainwindow.h
src
    CMakeLists.txt
    main.cpp
    mainwindow.cpp

字符串
CMakkeLists.txt(root):

cmake_minimum_required(VERSION 3.7)
project(Quick3D VERSION 0.1 LANGUAGES CXX)

add_executable(${PROJECT_NAME} src/main.cpp)
add_subdirectory(src)

target_include_directories(${PROJECT_NAME}
    PRIVATE
    ${PROJECT_SOURCE_DIR}/include
)


CMakeLists.txt(src目录):

target_sources(
    ${PROJECT_NAME}
    PRIVATE
    main.cpp
    mainwindow.cpp
)


错误代码:

CMake Warning (dev) at src/CMakeLists.txt:1 (target_sources):Policy CMP0076 is not set: target_sources() command converts relative paths
to absolute.  Run "cmake --help-policy CMP0076" for policy details.  Use
the cmake_policy command to set the policy and suppress this warning.

A private source from a directory other than that of target "Quick3D" has a
relative path.CMake (target_sources)
CMake Error at src/CMakeLists.txt:1 (target_sources):Cannot find source file:

  main.cpp

Tried extensions .c .C .c++ .cc .cpp .cxx .cu .mpp .m .M .mm .ixx .cppm
.ccm .cxxm .c++m .h .hh .h++ .hm .hpp .hxx .in .txx .f .F .for .f77 .f90
.f95 .f03 .hip .ispc

j2qf4p5b

j2qf4p5b1#

在CMake 3.7中,target_sources命令不会将相对路径转换为绝对路径。所有与该命令相关的源文件都将相对于创建**目标的目录进行解释。也就是说,

target_sources(${PROJECT_NAME}
    PRIVATE
    main.cpp
    mainwindow.cpp
)

字符串
from src/CMakeLists.txt相当于将这些源添加到顶级CMakeLists.txt文件中,并保持不变相对路径:

add_executable(${PROJECT_NAME} src/main.cpp)
# In the top-level CMakeLists.txt the following sources specification is wrong:
# it doesn't contain src/ subdirectory.
target_sources(${PROJECT_NAME}
    PRIVATE
    main.cpp
    mainwindow.cpp
)


在CMake 3.13中,当命令target_sources在被调用时立即开始将相对路径转换为绝对路径时,情况发生了变化。

CMake Warning (dev) at src/CMakeLists.txt:1 (target_sources):Policy CMP0076 is not set: target_sources() command converts relative paths
to absolute.  Run "cmake --help-policy CMP0076" for policy details.  Use
the cmake_policy command to set the policy and suppress this warning.


该警告表示在当前CMake版本中,target_sources命令会转换相对路径。但由于您在cmake_minimum_required调用中指定了3.7,因此CMake会保留3.7版本的行为,在该版本中不执行转换。
因此,简单的修复方法是将cmake_minimum_required规范更新到版本3.13或更高版本:

cmake_minimum_required(VERSION 3.13)

相关问题