4

I have a folder containing hpp and cpp files. I need to create a header file that includes all hpp files in the said folder:

#pragma once
#include "test_1.hpp"
#include "test_2.hpp"
#include "test_3.hpp"

can CMake do that?

Note:I am not going to put 'my' research work on your shoulder. I just need to know if such thing is possible, and possibly a link to where I can read from. My initial googling didn't show anything useful. thank you

1 Answer 1

8

You can use configure_file to fill a variable inside a template file. Create a template file containing the outline of the desired file and a placeholder for your include statements, e.g.:

list.hpp.in

#pragma once
@include_statements@

Then, in your CMakeLists.txt, you can fill the placeholder @include_statements@ with a list of files wrapped with #include statements.

project(test)
cmake_minimum_required(VERSION 2.8)

# Get list of some *.hpp files in folder include 
file(GLOB include_files include/*.hpp)

# Convert the list of files into #includes
foreach(include_file ${include_files})
  set(include_statements "${include_statements}#include \"${include_file}\"\n")
endforeach()

# Fill the template    
configure_file(list.hpp.in list.hpp)
Sign up to request clarification or add additional context in comments.

4 Comments

a common practice is to add the .in extension to the template that cmake uses. In your case configure_file(list.hpp.in list.hpp) It makes it easier to relate the input with the output.
Keep in mind that this solution requires running CMake to reflect any new files added to the include directory.
@Andrzej thanks, it works. include_files in CMakeLists.txt` includes absolute path. Is there any way to use the relative path?
Sure, check out the RELATIVE option of the file command cmake.org/cmake/help/v3.0/command/file.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.