默认情况下如何配置cmake以获取可执行文件 [英] How to configure cmake to get an executable not by default
问题描述
我有一个与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.txt
:
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屋!