How to configure cmake to get an executable not by default

醉酒当歌 提交于 2021-02-05 06:22:22

问题


I have a small project with cmake. I build a lib and an executable. on the development machine I want also an executable that cannot be build on other machines/environments.

e.g.:

<my-lib>
 | -- CMakeLists.txt
 |
 + -- src/             -> build the lib/archive
 |     |-- lib.c
 |     |-- lib.h
 |     |-- CMakeLists.txt
 |
 + -- tool             -> build the tool
 |     |-- tool.c
 |     |-- CMakeLists.txt
 |
 + -- tests            -> build the unit tests
 |     |-- tests.c
 |     |-- CMakeLists.txt

I added CMakeLists.txt to all directories. Also an add_executable to the tests. Now the unit-test executable is build by default. But I want to exclude it from default target.

CMakeLists.txt in tests:

find_library (CUNIT_LIB cunit)
include_directories (${Cunit_INCLUDE_DIRS} "${PROJECT_SOURCE_DIR}/src")

set (CMAKE_C_FLAGS "-O2 -Wall -Werror")

add_executable (unit-test tests.c)

target_link_libraries (unit-test my-lib cunit)

Has anyone a hint how to handle this? I don't want to build unit-test always!


回答1:


This is very simple: protect creation of executable by introducing an option/variable.

if (DEFINED WITH_UNIT_TEST)
  find_library (CUNIT_LIB cunit)
  include_directories (${Cunit_INCLUDE_DIRS} "${PROJECT_SOURCE_DIR}/src")

  set (CMAKE_C_FLAGS "-O2 -Wall -Werror")

  add_executable (unit-test tests.c)

  target_link_libraries (unit-test my-lib cunit)
endif ()

Now when invoking CMake, one would have to explicitly specify -DWITH_UNIT_TEST, so that unit-test target is built, while by default it will never be build. For alternative approach, see comments.




回答2:


There is a property EXCLUDE_FROM_ALL for such task.

You can write:

set_target_properties(unit-test PROPERTIES EXCLUDE_FROM_ALL TRUE)


来源:https://stackoverflow.com/questions/20500118/how-to-configure-cmake-to-get-an-executable-not-by-default

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