How to parse CMakeLists.txt files?

I would like to know if there’s a way to parse the content of CMakeLists.txt files and print out the targets and its content. I want to print out the content of set(), add_executable() and add_library(). For example:



Is it possible to simply print out what’s inside of the target?

When do you want this information? If at configure time, I would suggest making your own wrapper for add_* that tracks the arguments to it:

function (my_add_executable)
  # analyze ${ARGN} as needed
endfunction ()

If you just want to do some one-off processing, cmake --trace-expand can work. If you want more structured information, I would recommend the file-api mechanism.

Thank you for your response. At this point I would like to have this information for one-off processing. I tried cmake --trace-expand, but I believe file-api is what I need as I did take a look into it. As I understood I should use codemodel object in order to retrieve this information as a json file. That’s exactly what I want, to have the target information in a machine readable format. Perfect. However, I am stuck with the implementation part. I read that I should create a query dir and after the reruning cmake the reply dir will be created with all the json files. I tried it but didn’t really get an output. So, could you please help me with this part? Thanks.

I’m not familiar with the actual use of file-api. @brad.king?

The simplest usage is:

$ mkdir build
$ cd build
$ mkdir -p .cmake/api/v1/query
$ touch .cmake/api/v1/query/codemodel-v2
$ cmake /path/to/src ...
$ ls .cmake/api/v1/reply

This is an example of “v1 Shared Stateless Query Files” explained in the cmake-file-api(7) documentation. This style query is mainly for manual testing. A real application or IDE should use one of the “v1 Client” style queries, whose lifetime and ownership by a particular client are well-defined.