如何在 Cmake 接口库中包含特定标头?

问题描述 投票:0回答:1

这里是带有代码的存储库的链接:https://github.com/BrilStrawhat/cmake-interface_lib_question

我在CMake文档中找到了一个接口库:https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#interface-libraries

但它们就是不按我的预期工作。我无法指定和包含头文件,但只能包含整个目录。

提前致谢。

CMakeLists.txt:

cmake_minimum_required(VERSION 3.27)
project(interface_lib_test)

add_library(interface_lib_test INTERFACE)

# ref: https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#interface-libraries
target_sources(interface_lib_test INTERFACE
  FILE_SET HEADERS # useless line
  BASE_DIRS inc # same as target_include_directories
  FILES inc/prod.h # useless line
)

add_library(platform2 INTERFACE)

target_sources(platform2 PUBLIC
  FILE_SET HEADERS
  BASE_DIRS platform2
  FILES platform2/platform.h
)

add_executable(exe1 src/main.c)
target_link_libraries(exe1 platform2 interface_lib_test)

src/main.c:

#include <stdio.h>
#include <prod.h>

int main(void) {
    printf("%d\n", PLAT);
    return 0;
}

inc/prod.h:

#include "platform.h"

int prod(void);

inc/platform.h:

#define PLAT 1

platform2/platform.h:

#define PLAT 2

现在,如果运行 cmake,它会构建一个程序,并且包含位于 inc/ 中但不位于 platform2/ 中的 platform.h。 如何仅通过更改 CMakeLists.txt 文件来强制 cmake 从 platform2/ 包含 platform.h?

预计:

./exe1
2

实际:

./exe1
1
cmake cross-platform
1个回答
0
投票

使用双引号,指令#include "platform.h"首先在当前目录中搜索头文件,然后才在包含目录中搜索它。您可能想使用 <>。非常感谢您的回答 https://stackoverflow.com/users/3440745/tsyvarev

需要使用

#include <platform.h>

而不是

#include "platform.h"
© www.soinside.com 2019 - 2024. All rights reserved.