1

I have a grammar file grammar.peg that needs to be turned into grammar.inc where the grammar is wrapped into a C++ string of the form

namespace mynamespace
{
constexpr const char* headerSectionGrammar = R"(

here comes the grammar.peg contents

)";
}

At the moment, I do this during the CMake configuration with something like this

file(READ "grammar.peg" GRAMMAR_PEG)
string(PREPEND GRAMMAR_PEG "namespace mynamespae\n{\nconstexpr const char* headerSectionGrammar = R\"(\n")
string(APPEND GRAMMAR_PEG "\n)\"\;\n}\n")
file(WRITE "grammar.inc" ${GRAMMAR_PEG})

which works fine. The only downside is that when I change something in grammar.peg, I must not forget to re-run CMake to recreate grammar.inc.

Question: Is there a way to make this dependent on changes in grammar.peg so that it is re-run automatically while building the project? There are two critical aspects:

  1. There cannot be any additional thing in grammar.peg like a ${var} that gets replaced, because I'm using the peg file with a linter that expects a correct grammar file. Therefore, CMake's configure_file is afaik not an option
  2. I don't want to use any OS-specific commands (like awk) because we compile this under Linux, Mac OS, and Windows. When I rely on CMake's capabilities only, there much less trouble.

I've not used CMake generator expressions much, but they look promising. Maybe someone can give me a pointer in the right direction.

halirutan
  • 4,281
  • 18
  • 44
  • Aside from `configure_file` there are other approaches for automatically re-run CMake on a file changed. See more in the duplicate question and its answers. Note, that even approach with `configure_file` is not bad in your case: It is unrelated whether your file contains CMake substitution or not. – Tsyvarev Jun 02 '20 at 17:35
  • You could also use `add_custom_command` to run the command `${CMAKE_COMMAND} -P script.cmake` (CMake script mode). The `script.cmake` file would simply contain your CMake functions. – Kevin Jun 02 '20 at 18:16
  • Thank both of you for your suggestions. I wish I had found the linked duplicate earlier because `CMAKE_CONFIGURE_DEPENDS` is exactly what I was looking for. – halirutan Jun 02 '20 at 18:34

0 Answers0