Build custom target by default in CMake

こ雲淡風輕ζ 提交于 2021-01-07 02:36:23

问题


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.


回答1:


Use ALL option for build the target by default:

add_custom_target(bar ALL)



回答2:


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
)



回答3:


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.



来源:https://stackoverflow.com/questions/65525407/how-do-i-compile-and-integrate-cppcheck-with-cmake-on-vs-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!