Alan Chambers
Alan Chambers

Reputation: 21

How to keep CMake generated files?

I'm using add_custom_command() to generate some files. ninja clean removes them, as it should. One of the files is intended as a default/example implementation, to be modified by the user. It is only generated if it does not already exist. I would like for ninja clean not to remove this file.

I have tried a number of things but without success:

I previously generated the example implementation and just let the user copy it or model their code on it. This works, but isn't entirely satisfactory. Is my use-case so unlikely that CMake doesn't support it?

Upvotes: 2

Views: 872

Answers (3)

For those, who come here a long time after the original question was asked (like me), I'll write my solution:

The tool called in add_custom_command generates two files with identical content:

  • one that is saved in sources, never mentioned anywhere
  • and one that's marked as byproduct, and then is depended on

So the first one is the file we wanted in the first place. And the second one is actually used in build process, and gets deleted on clean.

For me the issue is that I actually want to save generated files in VCS so I can track changes. And this approach gives ne what I need.

Upvotes: 0

Bernhard
Bernhard

Reputation: 3694

If it is an example for the user, it should not be in your build folder, but in the install folder. I don't see why you would need add_custom_command or the other commands you listed.

Therefore, you have to provide install() instructions. You can then call make install. Cleaning will not remove those and only installing again will overwrite them if necessary.

Upvotes: 0

I am afraid you requirment (conceptually, have make create something which make clean does not remove) is rather unusual. I can think of two potential solutions/workarounds.

One, move the file's generation to CMake time. That is, create it using execute_process() instead of add_custom_command(). This may or may not be possible, based on whether the file-generation process (the current custom command) depends on the rest of the build or not.

Two, totally hide the example file's existence from CMake. That is, have the custom command also generate some other file (maybe just a timestamp file) and have its driving custom target depend on that one instead. Do not list the example file as ither the custom command's dependency, output, or byproduct. That way, nothing will depend on it and neither CMake nor Ninja should not care whether it exists or not, so they will not complain or try to clean it up.

Upvotes: 2

Related Questions