Mircea Ispas
Mircea Ispas

Reputation: 20790

Get the list of CMake configure_file calls

A bit of context first - I'm working on converting a CMake build system to an internal build system. For this I iterate BUILDSYSTEM_TARGETS and use get_property to get all the properties I need and everything works fine, except some files are missing from the build. After checking the CMakeLists.txt files from the original build system I realized configure_file is used in many and quite random places.

I assume CMake is storing configure_file calls internally. If this is the case, is it possible to access this?

Upvotes: 0

Views: 205

Answers (2)

Tsyvarev
Tsyvarev

Reputation: 66118

You could redefine configure_file as a function (or macro) at the beginning of the project's CMakeLists.txt. That way allows you to run arbitrary code every time the function is invoked in the project.

Inside redefining function you could implement the logic which you need. For call original function in the redefining one, use underscore-prefixed name (_configure_file):

function(configure_file input output)
  # ...
  # Do something with the 'output' file. E.g. add it to the global list.
  # ...

  # After custom processing call original function with all parameters.
  _configure_file(${input} ${output} ${ARGN})
endfunction()

Note, that generally redefining CMake functions is discouraged (at least, the underscored version of a function is an undocumented feature). But for debugging purposes it looks reasonable. Moreover, debugging was the primary reason to introduce such underscored functions: https://gitlab.kitware.com/cmake/cmake/-/issues/23482

Upvotes: 1

starball
starball

Reputation: 51943

Tsyvarev's answer of redefining configure_file works, but be aware that Craig Scott (one of the maintainers of CMake) has an article recommending against redefining CMake commands. Using the internal underscore-prefixed commands is relying on undocumented behaviour that can change in future versions. Using this trick can also result in infinite recursion.

While for your scenario it works fine, if you want to avoid using that trick, you can use the --trace* arguments to the cmake command.

--trace puts cmake in trace mode, which will print a trace of all calls made and from where.

--trace-expand is like --trace, but with variables expanded.

--trace-format=<format> lets you choose between human (a human readable format (the default value)), or json-v1, which prints JSON.

--trace-redirect=<file> puts cmake in trace mode and redirects trace output to a file instead of stderr.

So you could use the human format and grep for configure_file, or you could use the json-v1 format and write a script in a lanugage of your choice to search the JSON for calls to configure_file. You could also possibly use a comandline tool like jq to do the search.

Upvotes: 2

Related Questions