繁体   English   中英

CMake:在其他目录中找不到我的 header 文件

[英]CMake: can't find my header file in a different directory

我有一个 CMake 项目,其中包含以下相关文件夹:

project_folder
-src
|--main.c
peripherals
|--something.h
|--something.c

我在project_folder中的 CMake 包括:

add_subdirectory(peripherals)

if (NOT $ENV{TARGET_SOURCES} STREQUAL "")
    target_sources(app PRIVATE $ENV{TARGET_SOURCES})
else()
    target_sources(app PRIVATE src/main.c)
endif()

我在peripherals下的 CMake 包括:

add_library (peripherals something.c)

target_include_directories (peripherals PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

CMake 在src下:

add_executable(app main.c)
target_link_libraries(app PRIVATE peripherals)

我的项目正在完全构建,但是当我尝试在main.c中包含我的 header 文件时,我得到:

project_folder/peripherals/something.h:No such file or directory

在我的main.c文件中,我有#include "peripherals/something.h" 有谁知道如何解决这一问题? 我不确定我的#include 语句是否正确,并且我认为我的 CMakeLists 文件中缺少内容

您可以在main.cpp中执行"#include "../peripherals/i2c_test.h"

或者

project_folder的 CMake 中:

 target_include_directories(app ${CMAKE_CURRENT_SOURCE_DIR})

然后在 main.c 中:

#include <peripherals/i2c_test.h>
....

您需要定义可执行文件并将其与库“链接”:

# project_folder/CMakeLists.txt
add_subdirectory(peripherals)
add_subdirectory(src)


# project_folder/src/CMakeLists.txt
add_executable(my_executable main.c)
target_link_libraries(my_executable PRIVATE peripherals)

然后,您需要在main.c中正确包含 header - 因为您已经链接到包含peripherals目录的库,您现在可以直接包含它:

#include "something.h"

您的包含语句必须相对于包含的目录。

编辑:在您的示例中${CMAKE_CURRENT_SOURCE_DIR}是项目目录(您的 CMake 文件所在的位置)。

因此,您应该能够编写:

#include <peripherals/something.h>

您始终可以通过打印检查 cmake 变量的内容。 在您的 CMake 文件中,您可以编写:

message(STATUS ${CMAKE_CURRENT_SOURCE_DIR})

运行 cmake 时,您应该会在控制台 output 中看到打印的路径。

在 project_folder 中的 CMake 中:

 include_directories(src)

然后在 main.c 中:

#include <peripherals/i2c_test.h>

或者

在 project_folder 中的 CMake 中:

 include_directories(src/peripherals)

然后在 main.c 中:

#include <i2c_test.h>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM