Algorys
Algorys

Reputation: 1790

CMake Set option ON in just one CMakeLists

Actually, I've a project with different CMakeLists : one for compilations and one for unit tests (with goole test) for each "module". I've a structure like that :

module_1
--|src
--CMakeLists.txt // for compilation of module 1
--test
----|CMakeLists.txt // for unit tests of module 1

module_2
--|src
--CMakeLists.txt // for compilation of module 2
--test
----|CMakeLists // for unit tests of module 2

Now, my goal is to make only one CMakeLists.txt for each module and have compilation and unit test in the same CMakeLists.txt. So I make an OPTION in my CMakeLists.txt (for compilation) who trigger the test.

option(TEST_ENABLED
    "Tests Unitaires Core"
    OFF
)
if(TEST_ENABLED)
    set...
endif()

It's working good for one CMakeLists. But if I build all my modules, the option is activate for each module (I hope you follow me).

cmake -DTEST_ENABLED=ON -G"Unix Makefiles" ../module1

And I trigger compilation with a server (Jenkins) with some $variables so I want to activate the options only for the main CMakeLists (the one who's called with cmake command line)

How I can do that ?

If you want more information, tell me

Thanks in advnace for help.

Upvotes: 1

Views: 2217

Answers (2)

Isammoc
Isammoc

Reputation: 893

About testing, my favorite way is enabling testing with two conditions :

  • Variable TEST_ENABLED is ON
  • Current project is the main project for cmake

The second condition may be tested with PROJECT_NAME and CMAKE_PROJECT_NAME

Source : https://stackoverflow.com/a/8587949/1380225

Sample :

if(TEST_ENABLED AND ("${PROJECT_NAME}" STREQUAL "${CMAKE_PROJECT_NAME}"))
    ...
endif()

Upvotes: 1

Tsyvarev
Tsyvarev

Reputation: 65870

Options and other user-provided parameters are set globally for a project, so they affect on all its parts.

You may use different options for different parts of you project:

module1/CMakeLists.txt:

option(TEST1_ENABLED
    "Test for module 1"
    OFF
)

...

Alternatively, in case of tests, you can use single user-supplied parameter enumerating all modules, for which option should be set:

CMakeLists.txt:

set(TESTS_LIST "" CACHE STRING "List of tests")

module1/CMakeLists.txt:

list(module_index FIND "module1" ${TESTS_LIST})
if(module_index EQUAL -1)
    set(TEST_ENABLED OFF) # No CACHE, so variable is local for the module1.
else()
    set(TEST_ENABLED ON)
endif()

if(TEST_ENABLED)
    ...
endif()

Possible usage:

cmake "-DTESTS_LIST=module1;module3" -G "Unix Makefiles" ..

This will enable testing for module1 and module3, but not for module2.

Upvotes: 2

Related Questions