gpt4 book ai didi

c++ - 使用 CMake 根据目录内容生成 header /代码的方法?

转载 作者:搜寻专家 更新时间:2023-10-31 01:38:05 29 4
gpt4 key购买 nike

假设我有一个类“base”,在子目录“dir”中我有“foo”、“bar”和“leg”,每个都有一个头文件和一个源文件并继承“base”,就像这样.

-base.hpp/cpp
-dir
|-foo.hpp/cpp
|-bar.hpp/cpp
|-leg.hpp/cpp

我想知道 Cmake 是否有办法在“dir”中找到标题,将它们包含在一个文件中,然后获取名称(不带扩展名)然后生成代码,这样生成的文件将是像这样的东西:

目录文件.hpp -

 #include “dir/foo.hpp”
#include “dir/bar.hpp”
#include “dir/leg.hpp”
void function();

目录文件.cpp -

 #include “dir_files.hpp”
void function()
{
do_something(foo);
do_something(bar);
do_something(leg);
}

最佳答案

您可以使用以下关键字/技巧:

CMake:

# "file" to find all files relative to your root location
file(GLOB SRC_H
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
"dir/*.h"
)

file(GLOB SRC_CPP
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
"dir/*.cpp"
)

# foreach to iterate through all files
foreach(SRC_H_FILE ${SRC_H})
message("header ${SRC_H_FILE}")

# You could build up your include part here
set(INCLUDE_PART "${INCLUDE_PART}#include <${SRC_H_FILE}>\n")
endforeach()

foreach(SRC_CPP_FILE ${SRC_CPP})
message("src ${SRC_CPP_FILE}")
endforeach()

message("${INCLUDE_PART}")

# Configure expands variables in a template file
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/HeaderTemplate.h.in.cmake"
"${CMAKE_BINARY_DIR}/HeaderTemplate.h"
)

HeaderTemplate.h.in.cmake:

// Template file

@INCLUDE_PART@
void function();

CMake 输出将是:

日志:

header dir/Test1.h
header dir/Test2.h
header dir/Test3.h
src dir/Test1.cpp
src dir/Test2.cpp
src dir/Test3.cpp
#include <dir/Test1.h>
#include <dir/Test2.h>
#include <dir/Test3.h>

HeaderTemplate.h

// Template file

#include <dir/Test1.h>
#include <dir/Test2.h>
#include <dir/Test3.h>

void function();

关于c++ - 使用 CMake 根据目录内容生成 header /代码的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324698/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com