I'd like to run a custom command with cmake. That sounds like an incredibly simple task/question, but it's frustrating how difficult it is to find an example.
Here's what I'm attempting to do:
$ cmake .
$ make
> Hello World! (Output)
In Gnu Make that's very easy:
bar:
echo Hello World!
But I'm trying to do this in cmake. Based on what I've been reading, I should be able to do that with the CMakeLists.txt
file below:
cmake_minimum_required(VERSION 3.6)
project(foo)
add_custom_target(bar)
add_custom_command(
TARGET bar
COMMAND "echo Hello World!"
)
Currently there is no work to do if I just call make
. I need to explicitly call make bar
. How can I add bar
to the all
recipe?
I've tried adding add_dependency(foo bar)
, but foo
is a non-existent target. If there is some super-target that I'm unaware of that would be perfect. Then I could just use that as the TARGET for my custom command and not bother with bar
.
Expanding on Tsyvarev's perfect answer, to simplify the cmakelists.txt file further we can do this:
cmake_minimum_required(VERSION 3.6)
project(foo)
add_custom_target(bar ALL
COMMAND "echo Hello World!"
)
This integrates the custom_command into the custom_target.
Use ALL
option for build the target by default:
add_custom_target(bar ALL)
When the custom command produces actually some stuff, instead of only print "Hello World", then the following might be appropriate.
add_custom_target(Work ALL DEPENDS that.txt)
add_custom_command(
OUTPUT that.txt
COMMAND generator --from this.txt --produce that.txt
DEPENDS this.txt
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With