假设我有一个“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" 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/