如何配置 cmake 以获取非默认的可执行文件 [英] How to configure cmake to get an executable not by default

查看:18
本文介绍了如何配置 cmake 以获取非默认的可执行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 cmake 的小项目.我构建了一个库和一个可执行文件.在开发机器上,我还想要一个无法在其他机器/环境上构建的可执行文件.

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.

例如:

<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

我将 CMakeLists.txt 添加到所有目录.还有一个 add_executable 到测试中.现在默认情况下构建单元测试可执行文件.但我想从默认目标中排除它.

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.txttests 中:

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!

推荐答案

这很简单:通过引入选项/变量来保护可执行文件的创建.

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 ()

现在在调用 CMake 时,必须明确指定 -DWITH_UNIT_TEST,以便构建 unit-test 目标,而默认情况下永远不会构建.有关替代方法,请参阅评论.

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.

这篇关于如何配置 cmake 以获取非默认的可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆