Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build custom target by default in CMake

Tags:

cmake

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.

like image 524
Stewart Avatar asked May 10 '17 07:05

Stewart


3 Answers

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.

like image 133
Stewart Avatar answered Oct 20 '22 04:10

Stewart


Use ALL option for build the target by default:

add_custom_target(bar ALL)
like image 38
Tsyvarev Avatar answered Oct 20 '22 02:10

Tsyvarev


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
)
like image 34
Frank-Rene Schäfer Avatar answered Oct 20 '22 04:10

Frank-Rene Schäfer