Usage of Ragel in Qt project

Recently I had an opportunity to work with Ragel State Machine Compiler in my Qt project (There was a requirement to parse binary protocol), and the question was, how to integrate Ragel source files in the project conveniently. After all, I've read about qmake's QMAKE_EXTRA_COMPILERS facility, which does the job very well.

So, the final recipe: create the file ragel.pri:

ragel.pri
# ------------ ragel compiler settings ------------
 
# output file: place in build dir, with "ragel_" prefix and without ".rl" suffix
ragel.output = $$OUT_PWD/ragel_${QMAKE_FILE_IN_BASE}    
 
# ragel input files should be given in RAGEL_FILES variable
ragel.input = RAGEL_FILES
 
# command that should be executed to compile file
ragel.commands = ragel ${QMAKE_FILE_IN} -o ${QMAKE_FILE_OUT}
 
# variable to which generated filenames should be added
ragel.variable_out = SOURCES
 
# name (for internal qmake usage)
ragel.name = RAGEL
 
 
 
# add ragel as qmake extra compiler
QMAKE_EXTRA_COMPILERS += ragel

And include this file to your main .pro file, like this:

my_project.pro
include(ragel.pri)
 
# ... the rest of project

After this, you can add files to be processed with ragel to RAGEL_FILES variable:

my_project.pro
include(ragel.pri)
 
RAGEL_FILES += path/to/my_ragel_file.cpp.rl
 
# ... the rest of project

Now, during the build process, the file path/to/my_file.cpp.rl will be processed by ragel into output file my_build_dir/ragel_my_file.cpp and automatically added to SOURCES variable. Works great.

Of course, you need Ragel to be installed at your machine for the above to work.