We can define an option switch to control the internal configuration logic, for example:
option("tests", {default = false, description = "Enable Tests"})
target("foo")
set_kind("binary")
add_files("src/*.cpp")
if has_config("tests") then
add_defines("TESTS")
end
Then, we can enable this custom option in the command line, so that the macro definition of -DTESTS is automatically added when the foo target is compiled.
$ xmake f --tests=y
$ xmake
The above option configuration is relatively simple, so we use a single-line simplified writing method, and we can also use the complete domain configuration writing method.
option("tests")
set_default(false)
set_description("Enable Tests")
We can also use add_options to bind options to a specified target directly without using has_config and add_defines to set them manually.
In this way, when the option is enabled, all associated settings in the tests option will be automatically set to the bound target.
option("tests")
set_description("Enable Tests")
set_default(false)
add_defines("TEST")
target("foo")
set_kind("binary")
add_files("src/*.cpp")
add_options("tests")
In the above example, when tests is enabled, the foo target will automatically be added with -DTEST.
set_values to provide choices (menu)set_default(value): Set default value (bool or string)set_showmenu(true/false): Show in xmake f --menuset_description("desc"): Set descriptionset_values("a", "b", "c"): Set selectable values (menu)add_defines("FOO"): Add macro when enabledadd_links("bar"): Add link library when enabledadd_cflags("-O2"): Add compile flag when enabledadd_deps("otheropt"): Depend on other options, often used with on_check/after_checkbefore_check/on_check/after_check: Custom check logic, can enable/disable options dynamicallyoption("feature_x")
set_default(false)
on_check(function (option)
if has_config("feature_y") then
option:enable(false)
end
end)
In on_check, after_check, etc., you can use the option instance APIs:
option:name() get option nameoption:value() get option valueoption:enable(true/false) enable/disable optionoption:enabled() check if enabledoption:get("defines") get config valueoption:set("defines", "FOO") set config valueoption:add("links", "bar") append config valueadd_options("opt1", "opt2") to bind options to targetshas_config("opt") for conditional logic in target scopeoption("enable_lto")
set_default(false)
set_showmenu(true)
set_description("Enable LTO optimization")
add_cflags("-flto")
target("foo")
add_options("enable_lto")
option("rootdir")
set_default("/tmp/")
set_showmenu(true)
set_description("Set root directory")
target("foo")
add_files("$(rootdir)/*.c")
option("arch")
set_default("x86_64")
set_showmenu(true)
set_description("Select architecture")
set_values("x86_64", "arm64", "mips")