cmake: setting default values for arguments

2019-07-18 05:31发布

My UNIX Makefile is as follows:

   param=0

   run:
       ./foo -r "fun($(param))"

So if I do make run, I get ./foo - r "fun(0)" and for make run param=10, I get ./foo -r "fun(10)".

Now I want to generate similar Makefile using cmake.

   add_custom_target(
    run 
    ./foo -r "\"fun($(param))\""
   )

How do I set the default value for param within cmake configuration file?

标签: cmake
2条回答
混吃等死
2楼-- · 2019-07-18 05:50

The concept in CMake is a bit different. You can define "cache variables" (basically variables that are remembered for subsequent builds in the same build dir, and can be customized by users) that come with default values and documentation strings and such. These can then be changed either by passing -D name:type=value options to cmake, or using one of the friendlier frontends (e.g. ccmake, the curses UI for CMake).

Example based on your question:

SET(param 0 CACHE STRING "Test variable defaulting to '0'")
# ...
add_custom_target(run ./foo -r "\"fun(${param})\"")

You'll find more details in the exhaustive docs for CMake.

PS. this is for variables inside CMake and specifically CMakeLists.txt itself; the possibility to change the value is not carried over into the generated Makefile as far as I can tell. I'm not sure that's possible in the first place because it probably wouldn't be compatiable with all of the targets supported by CMake (e.g. Visual Studio projects and what not). In any case, CMake doesn't seem to have been designed for generating build files used independently of CMake.

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-18 06:03

Use

set (projectname_param 0)

to set it.

查看更多
登录 后发表回答