使用CMake生成基于目录内容的头/代码的方法

Way to use CMake to generate header/code based on contents of a directory?

本文关键字:代码 方法 CMake 于目录 使用      更新时间:2023-10-16

假设我有一个类" base ",在子目录" dir "中我有" foo ", " bar "answers" leg ",每个都有一个头文件和一个源文件,继承了" base ",像这样。

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

我想知道是否有一种方法与Cmake在"dir"中找到头,将它们包含在一个文件中,然后取名称(没有扩展名),然后生成代码,使结果文件类似:

dir_files.hpp——

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

dir_files.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();
相关文章: