Issue
I do not really know cmake, but I am trying to setup some sort of an option in CMake - a single line that can be commented or uncommented - and depending on its existence, an additional file should be included in the set of source files.
So, based on:
... I came up with following example CMakeFiles.txt
:
project(MyApp)
option(ADD_EXTRA_FILE TRUE)
set(MyApp_sources
main.c
file1.c
file2.c
)
if(NOT ADD_EXTRA_FILE)
set(MyApp_sources ${MyApp_sources} "extra_file.c")
endif(NOT ADD_EXTRA_FILE)
message(STATUS "ADD_EXTRA_FILE: ${ADD_EXTRA_FILE}")
message(STATUS "MyApp_sources: ${MyApp_sources}")
When I run this, I would expect ADD_EXTRA_FILE
to be TRUE
, and therefore if(NOT ADD_EXTRA_FILE)
should evaluate to FALSE
, and therefore the extra file should not be added; however:
$ cmake .
-- ADD_EXTRA_FILE: OFF
-- MyApp_sources: main.c;file1.c;file2.c;extra_file.c
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp
... it turns out, ADD_EXTRA_FILE
is OFF
(?), and apparently if(NOT ADD_EXTRA_FILE)
evaluates to TRUE
, and the extra file is added anyways.
Is it possible to achieve what I want in Cmake - and if so, how?
Solution
I'd personally won't recommend usage of plain set
for option. @sdbbs did everything right except cleaning cache. If one doesn't provide option manually it's set once and value won't change after just running cmake
to reconfigure project.
So the following work as expected:
project(MyApp)
option(ADD_EXTRA_FILE "include extra file" ON)
set(MyApp_sources
main.c
file1.c
file2.c
)
if(NOT ADD_EXTRA_FILE)
set(MyApp_sources ${MyApp_sources} "extra_file.c")
endif(NOT ADD_EXTRA_FILE)
message(STATUS "ADD_EXTRA_FILE: ${ADD_EXTRA_FILE}")
message(STATUS "MyApp_sources: ${MyApp_sources}")
with the following output:
> cmake ..
-- The C compiler identification is GNU 9.4.0
-- The CXX compiler identification is GNU 9.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- ADD_EXTRA_FILE: ON
-- MyApp_sources: main.c;file1.c;file2.c
-- Configuring done
-- Generating done
PS
Of course, from the sanity point ADD_EXTRA_FILE
should be OFF
by default and if(ADD_EXTRA_FILE)
adds the file.
Answered By - c4pQ Answer Checked By - Candace Johnson (WPSolving Volunteer)