【问题标题】:Way to use CMake to generate header/code based on contents of a directory?使用 CMake 根据目录内容生成标头/代码的方法?
【发布时间】:2015-10-25 00:05:53
【问题描述】:

假设我有一个类“base”,在子目录“dir”中我有“foo”、“bar”和“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 command)?您遇到的具体问题是什么?我怀疑有人会为你写剧本……
  • 我真的是 CMake 的菜鸟。我不太明白它的语法,我希望有人推荐一些在这里有用的命令。

标签: c++ cmake


【解决方案1】:

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

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();

【讨论】:

  • 这似乎是解决问题的好方法。我想没有任何特定的功能可以做到这一点,但我想无论如何它都会是一个小众功能。
  • 对于“生成代码”部分,我使用了 STRING REPLACE 命令删除了文件扩展名。
  • @MamaLuigi 是的,这个功能似乎太具体了,不能期望内置到 CMake 中。但是,您始终可以创建自己的 functionmacro
  • @Mama Luigi get_filename_component 提供了获取各种文件名组件(如扩展名或文件名)的可能性
  • @Denis Blank 谢谢。我确实在最终解决方案中使用了该命令。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 2019-06-17
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
相关资源
最近更新 更多