execute_process() vs add_custom_command()

Simple question:
When should I use one of them?

Or a little biased:
Why/When should I use execute_process() over add_custom_command()?

The difference between those two is, that execute_process() works at configure time (therefore will be executed with every cmake configure) and add_custom_command() works at build time (and is only executed when the dependencies change)

I only need add_custom_command(), but beginners tend to use execute_process() since it is easier to understand (and easier to find via doc/google), but dependencies are usually omitted.

It depends :slight_smile: . If it’s something that should happen automatically during the build, then you definitely want add_custom_command. If you’re running a program to get the default value or other system introspection (say, numpy's header directory or available memory), this is execute_process's job. If you’re generating sources, then you usually want add_custom_command, but if the generation is a combination of:

  • expensive
  • rarely changes
  • hard to get dependencies right

then execute_process may work better.

Both have their place, but choosing one over the other requires knowing more about the situation in which it is needed.

I really don’t like using execute_process unless I have to. Because execute_process is done during the configure stage of cmake. To me a very quick configure stage is really important. Adding too much logic to your configure step slows down iteration speed which is crucial for rapid development/testing. Also execute_process tends to be slower on Windows (Why is cmake on Linux so much faster than on Windows?) depending on what you are doing.

I like using add_custom_command since it happens during the build step and can be parallelized. Even if your custom task is single threaded the build can still potentially be running other tasks and whatnot.

Overall my opinion is:
1.) Make sure you really need to do this in the first place. Get another person’s opinion.
2.) Document what you are doing. Make sure other people understand what your custom build task is doing.
3.) Choose add_custom_command over execute_process if possible

1 Like