ChatGPT解决这个技术问题 Extra ChatGPT

Adding command line options to CMake

I'm building a large library using CMake, and I would like users to be able to selectively enable/disable certain parts of my build process.

How can I add command-line options to my CMake build, e.g. so that users may type something like cmake --build-partone --nobuild-parttwo --dothis=true --dothat=false ..?

Apparently the OPTION keyword will create variables that can be set from the CMake GUI, but I can't figure out how to do this from the command line.

Thank you for your question as it answered my question with regards to the purpose of cmake option. So, i see now it is for GUI

P
Peter Mortensen

Yeah, you should use the option command. You can set options from the command line this way:

//CMakeLists.txt
option(MyOption "MyOption" OFF)

//Command line
cmake -DMyOption=ON MyProjectFolder

Note that -DMyOption must come before the path.


... and cmake MyProjectFolder -DMyOption does not turn the option on (or off)
put -DMyOption before MyProjectFolder and take a try?
Use -DMyOption=ON or -DMyOption=OFF to turn on or off.
I just noticed as I was trying to build a third party module that items set with "set(NAME blahblah)" in CMakeLists.txt are overridable with -DNAME=overridingValue on the cmake command line,
P
Peter Mortensen

Just a little correction:

If you have other variables to pass, it is recommended to indicate the type of these:

//CMakeLists.txt
option(MyOption "MyOption" OFF)

//Command line
cmake -DMyOption:BOOL=ON MyProjectFolder -D...