### Install Dependency with Simplified Configuration Source: https://xmake.io/zh/api/description/global-interfaces.html Command-line example for installing a dependency with a simplified configuration syntax using xrepo. ```sh xrepo install boost[iostreams,system,thread] ``` -------------------------------- ### Complete Example for Self-Installing Package Source: https://xmake.io/zh/posts/xmake-update-v2.8.6.html A comprehensive example demonstrating the configuration for xmake's own source package, including setting base name, prefix directory, and handling source files from a Git repository with custom installation commands. ```lua xpack("xmakesrc") set_formats("runself") set_basename("xmake-v$(version)") set_prefixdir("xmake-$(version)") before_package(function (package) import("devel.git") local rootdir = path.join(os.tmpfile(package:basename()) .. ".dir", "repo") if not os.isdir(rootdir) then os.tryrm(rootdir) os.cp(path.join(os.projectdir()), rootdir) git.clean({repodir = rootdir, force = true, all = true}) git.reset({repodir = rootdir, hard = true}) if os.isfile(path.join(rootdir, ".gitmodules")) then git.submodule.clean({repodir = rootdir, force = true, all = true}) git.submodule.reset({repodir = rootdir, hard = true}) end end local extraconf = {rootdir = rootdir} package:add("sourcefiles", path.join(rootdir, "core/**|src/pdcurses/**|src/luajit/**|src/tbox/tbox/src/demo/**"), extraconf) package:add("sourcefiles", path.join(rootdir, "xmake/**"), extraconf) package:add("sourcefiles", path.join(rootdir, "*.md"), extraconf) package:add("sourcefiles", path.join(rootdir, "configure"), extraconf) package:add("sourcefiles", path.join(rootdir, "scripts/*.sh"), extraconf) package:add("sourcefiles", path.join(rootdir, "scripts/man/**"), extraconf) package:add("sourcefiles", path.join(rootdir, "scripts/debian/**"), extraconf) package:add("sourcefiles", path.join(rootdir, "scripts/msys/**"), extraconf) end) on_installcmd(function (package, batchcmds) batchcmds:runv("./scripts/get.sh", {"__local__"}) end) ``` -------------------------------- ### Install Package with Mirror Proxy Source: https://xmake.io/zh/guide/package-management/network-optimization.html Example of installing a package using xrepo, demonstrating how mirror proxy rules can redirect downloads to faster mirror hosts. ```bash $ xrepo install libpng > curl https://hub.fastgit.org/glennrp/libpng/archive/v1.6.37.zip -o v1.6.37.zip ``` -------------------------------- ### Create and Run Application Instance (Lua) Source: https://xmake.io/zh/api/scripts/extension-modules/core/ui/application.html Provides a complete example of creating an application instance, defining its initialization logic, and then running the application to start the event loop. This is a fundamental pattern for using the application module. ```lua local demo = application() function demo:init() application.init(self, "demo") self:background_set("blue") self:insert(self:main_dialog()) end -- 启动应用程序 demo:run() ``` -------------------------------- ### NSIS Spec File Example Source: https://xmake.io/zh/api/description/xpack-interfaces.html An example of a `makensis.nsi` file demonstrating the use of built-in variables like `${VERSION}` and `${PACKAGE_NAME}` for defining installer properties. ```plaintext VIProductVersion "${VERSION}.0" VIFileVersion "${VERSION}.0" VIAddVersionKey /LANG=0 ProductName "${PACKAGE_NAME}" VIAddVersionKey /LANG=0 Comments "${PACKAGE_DESCRIPTION}" VIAddVersionKey /LANG=0 CompanyName "${PACKAGE_COMPANY}" VIAddVersionKey /LANG=0 LegalCopyright "${PACKAGE_COPYRIGHT}" VIAddVersionKey /LANG=0 FileDescription "${PACKAGE_NAME} Installer - v${VERSION}" VIAddVersionKey /LANG=0 OriginalFilename "${PACKAGE_FILENAME}" ``` -------------------------------- ### Add Install Tips for Manual Steps Source: https://xmake.io/zh/guide/best-practices/package-spec.html Provide user guidance for specific installation requirements, such as manual EULA acceptance, using `set_installtips(...)`. This helps prevent user errors during installation. ```lua set_installtips("This package requires manual EULA acceptance before first use.") ``` -------------------------------- ### Package Debug Build Rule Example Source: https://xmake.io/zh/guide/package-management/using-official-packages.html Example of how to define a custom installation rule for a package (`openssl`) that supports debug builds. ```lua package("openssl") on_install("linux", "macosx", function (package) os.vrun("./config %s --prefix=\" %s \"", package:debug() and "--debug" or "", package:installdir()) os.vrun("make -j4") os.vrun("make install") end) ``` -------------------------------- ### Get Specific Command Help in Xmake Source: https://xmake.io/zh/guide/best-practices/faq.html Example of how to get parameter information for a specific command like 'run'. ```sh $ xmake run --help ``` -------------------------------- ### Install Qt Application on Windows Source: https://xmake.io/zh/posts/xmake-update-v2.5.1.html Build and install a Qt application on Windows using xmake. The `install` command automatically invokes windeployqt.exe. ```bash $ xmake $ xmake install -o d:\installdir ``` -------------------------------- ### Compile and Install xmake from Source Source: https://xmake.io/zh/posts/quickstart-1-installation.html Compiles and installs xmake from its source code. It's recommended not to install as root. This method installs to ~/.local/xmake and requires sourcing the profile. ```bash $ git clone --recursive https://github.com/xmake-io/xmake.git $ cd ./xmake $ ./scripts/get.sh __local__ $ source ~/.xmake/profile ``` -------------------------------- ### Package Installation with Scheme Fallback Source: https://xmake.io/zh/posts/xmake-update-v3.0.7.html Simulates the package installation process, showing how Xmake attempts a binary installation and falls back to a source build if the initial attempt fails. ```console note: install or modify (m) these packages (pass -y to skip confirm)? -> ninja 1.13.1 [host] please input: y (y/n/m) => download https://github.com/ninja-build/ninja/releases/download/v1.13.1/ninja-win.zip .. ok => install ninja 1.13.1 (binary) .. failed => download https://github.com/ninja-build/ninja/archive/refs/tags/v1.13.1.tar.gz .. ok => install ninja 1.13.1 (source) .. ok ``` -------------------------------- ### Get package installation directory Source: https://xmake.io/zh/api/scripts/package-instance.html Retrieve the path to the package's installation directory. This can also be used to get subdirectories, and if they don't exist, they will be created. ```lua -- returns the installation directory package:installdir() -- returns the subdirectory include inside the installation directory package:installdir("include") -- returns the subdirectory include/files package:installdir("include", "files") ``` -------------------------------- ### Meson Install Source: https://xmake.io/zh/api/scripts/extension-modules/package/tools.html Installs a package using Meson's setup, compile, and install steps. Supports custom configuration and package dependencies. ```APIDOC ## meson.install ### Description Installs a package using Meson's setup, compile, and install steps. Supports custom configuration and package dependencies. ### Method `Meson.install(package: , configs: , opt:
)` ### Parameters #### Path Parameters - `package` (package) - Required - Package instance object - `configs` (table) - Required - Meson configuration parameter list - `opt` (table) - Optional - Option parameters, supporting: - `packagedeps` - Package dependency list ### Request Example ```lua import("package.tools.meson").install(package, configs, {packagedeps = packagedeps}) ``` ### Response No return value. ``` -------------------------------- ### Server Configuration Example Source: https://xmake.io/zh/guide/extras/build-cache.html Example of the `server.conf` file, showing how to configure the listening port, working directory, log file, and authentication tokens. ```json { "distcc_build" = { "listen" = "0.0.0.0:9692", "workdir" = "/Users/ruki/.xmake/service/server/remote_cache" }, "known_hosts" = { }, "logfile" = "/Users/ruki/.xmake/service/server/logs.txt", "tokens" = { "590234653af52e91b9e438ed860f1a2b" } } ``` -------------------------------- ### Get Target Install Directory Source: https://xmake.io/zh/api/scripts/target-instance.html Retrieves the installation directory for the target file. Typically used in scripts like after_install for custom installation logic. ```lua target:installdir() ``` -------------------------------- ### Install xmake using One-Line Script Source: https://xmake.io/zh/posts/build-project-so-simply.html Installs xmake by executing a single bash command that downloads and runs the installation script from a GitHub URL. ```bash bash <(curl -fsSL https://raw.githubusercontent.com/tboox/xmake/master/scripts/get.sh) ``` -------------------------------- ### Install Packages Source: https://xmake.io/zh/guide/package-management/xrepo-cli.html Install one or more packages using `xrepo install`. Packages are downloaded and made available for your projects. ```sh xrepo install zlib tbox ``` -------------------------------- ### Configure Qt QuickApp Build Source: https://xmake.io/zh/posts/xmake-update-v2.5.1.html Example xmake.lua configuration for building a Qt Quick application. ```lua add_rules("mode.debug", "mode.release") target("demo") add_rules("qt.quickapp") add_headerfiles("src/*.h") add_files("src/*.cpp") add_files("src/qml.qrc") ``` -------------------------------- ### Install Xmake using wget Source: https://xmake.io/zh/guide/quick-start.html Installs Xmake using wget to download and execute the installation script. This is an alternative to curl for Unix-like systems. ```shell wget https://xmake.io/shget.text -O - | bash ``` -------------------------------- ### Set Installation Prefix Directory Source: https://xmake.io/zh/api/description/xpack-interfaces.html Define a prefix directory under the main installation directory where all package files will be installed. This allows for a nested structure, for example, `installdir/prefix/include`, `installdir/prefix/lib`, etc. ```lua xpack("xmake") set_prefixdir("prefix") ``` -------------------------------- ### Full UI Action Demonstration Source: https://xmake.io/zh/api/scripts/extension-modules/core/ui/action.html A complete example showcasing the creation of a UI application with windows, buttons, and event handling for different actions. It demonstrates setting up multiple buttons with distinct click handlers and managing the UI layout. Requires importing `core.ui.action`, `core.ui.button`, `core.ui.rect`, `core.ui.application`, and `core.ui.window`. ```lua import("core.ui.action") import("core.ui.button") import("core.ui.rect") import("core.ui.application") import("core.ui.window") local demo = application() function demo:init() application.init(self, "demo") self:background_set("blue") -- 创建窗口 local win = window:new("main", rect{1, 1, self:width() - 1, self:height() - 1}, "Action 演示") -- 创建按钮并设置不同的事件 local btn1 = button:new("btn1", rect{5, 5, 20, 1}, "< 按钮1 >") local btn2 = button:new("btn2", rect{30, 5, 20, 1}, "< 按钮2 >") -- 设置不同的事件处理器 btn1:action_set(action.ac_on_enter, function (v) print("按钮 1 被确认点击") end) btn2:action_set(action.ac_on_enter, function (v) print("按钮 2 被确认点击") end) -- 将按钮添加到窗口面板 local panel = win:panel() panel:insert(btn1) panel:insert(btn2) -- 选择第一个按钮 panel:select(btn1) self:insert(win) self._win = win end function demo:on_resize() self._win:bounds_set(rect{1, 1, self:width() - 1, self:height() - 1}) application.on_resize(self) end function main(...) demo:run(...) end ``` -------------------------------- ### Install Package with Meson Source: https://xmake.io/zh/api/scripts/extension-modules/package/tools.html Installs a package using Meson, which handles the setup, compilation, and installation process. It accepts configuration parameters and optional arguments like package dependencies. ```lua add_deps("meson", "ninja") on_install(function (package) local configs = {} table.insert(configs, "-Ddefault_library=" .. (package:config("shared") and "shared" or "static")) if package:is_debug() then table.insert(configs, "-Dbuildtype=debug") else table.insert(configs, "-Dbuildtype=release") end local packagedeps = {"zlib"} if package:config("openssl") then table.insert(packagedeps, "openssl") end import("package.tools.meson").install(package, configs, {packagedeps = packagedeps}) end) ``` -------------------------------- ### Client Configuration File Example Source: https://xmake.io/zh/guide/extras/distributed-compilation.html Configure the `client.conf` file to specify the addresses and authentication tokens of the distributed build servers the client should connect to. ```json { distcc_build = { hosts = { { connect = "192.168.22.168:9693", token = "590234653af52e91b9e438ed860f1a2b" }, { connect = "192.168.22.169:9693", token = "590234653af52e91b9e438ed860f1a2b" } } } } ``` -------------------------------- ### Configure, build, and install Xmake from source Source: https://xmake.io/zh/guide/quick-start.html Builds and installs Xmake from source code on Linux systems. This involves configuring, compiling, and then installing locally. ```shell ./configure make -j4 ./scripts/get.sh __local__ __install_only__ source ~/.xmake/profile ``` -------------------------------- ### Create Qt QuickApp Project Source: https://xmake.io/zh/posts/quickstart-6-build-qt-project.html Use the xmake create command with the qt.quickapp template to quickly scaffold a new Qt project with QML support. ```bash $ xmake create -t qt.quickapp test ``` -------------------------------- ### Example xmake.lua with Build Configuration Source: https://xmake.io/zh/guide/basic-commands/build-targets.html Illustrates basic xmake.lua configuration for debug and release modes, defining static and binary targets, and their dependencies. ```lua add_rules("mode.debug", "mode.release") target("foo") set_kind("static") add_files("src/foo.cpp") target("test") set_kind("binary") dd_deps("foo") --------------- 不正确的接口 add_files("src/main.cpp") ``` -------------------------------- ### Getting xmake Installation Directory Source: https://xmake.io/zh/api/scripts/builtin-modules/os.html Retrieve the directory path where the xmake main program script is installed. This is equivalent to the $(programdir) macro. ```lua print(path.join(os.programdir(), "file.txt")) ``` -------------------------------- ### Install a Package Source: https://xmake.io/zh/guide/package-management/package-management-in-project.html Use this command to download and install a specified package into the current project. ```sh xmake require tbox ``` -------------------------------- ### Specify Installation Directory with Prefix Source: https://xmake.io/zh/posts/safer-install-and-uninstall.html This Bash snippet shows how to specify a custom installation directory using the 'prefix' argument after building. This allows users to control where xmake is installed, for example, to '/usr/local'. ```bash make build; sudo make install prefix=/usr/local ``` -------------------------------- ### Complete Linking Example Source: https://xmake.io/zh/api/description/project-target.html A comprehensive example demonstrating rules, requirements, targets, dependencies, system links, frameworks, and link orders. ```lua add_rules("mode.debug", "mode.release") add_requires("libpng") target("bar") set_kind("shared") add_files("src/foo.cpp") add_linkgroups("m", "pthread", {whole = true}) target("foo") set_kind("static") add_files("src/foo.cpp") add_packages("libpng", {public = true}) target("demo") set_kind("binary") add_deps("foo") add_files("src/main.cpp") if is_plat("linux", "macosx") then add_syslinks("pthread", "m", "dl") end if is_plat("macosx") then add_frameworks("Foundation", "CoreFoundation") end add_linkorders("framework::Foundation", "png16", "foo") add_linkorders("dl", "linkgroup::syslib") add_linkgroups("m", "pthread", {name = "syslib", group = true}) ``` -------------------------------- ### Full Event Handling Example Source: https://xmake.io/zh/api/scripts/extension-modules/core/ui/event.html This comprehensive example demonstrates setting up a UI application, creating windows and labels, and handling various events including window resizing and key presses. It shows how to display event information and quit the application. ```lua import("core.ui.event") import("core.ui.rect") import("core.ui.label") import("core.ui.window") import("core.ui.application") local demo = application() function demo:init() application.init(self, "demo") self:background_set("black") -- 创建主体窗口 local body = window:new("window.body", rect{1, 1, self:width() - 1, self:height() - 1}, "主窗口") self:insert(body) -- 创建标签显示事件信息 local label = label:new('demo.label', rect{0, 0, 40, 5}, '这是一个测试') body:panel():insert(label) self._label = label end function demo:on_resize() self:body_window():bounds_set(rect{1, 1, self:width() - 1, self:height() - 1}) application.on_resize(self) end -- 处理事件 function demo:on_event(e) if e.type < event.ev_max then -- 显示事件信息 local event_info = string.format('type: %s; name: %s; code: %s; meta: %s', tostring(e.type), tostring(e.key_name or e.btn_name or 'none'), tostring(e.key_code or e.x or 0), tostring(e.key_meta or e.y or 0)) self._label:text_set(event_info) end -- 处理特定按键 if e:is_key("Esc") then self:quit() return true elseif e:is_key("Enter") then print("按下了 Enter 键!") return true end application.on_event(self, e) end function demo:body_window() return self:view("window.body") end function main(...) demo:run(...) end ``` -------------------------------- ### Add Xmake PPA and install on Ubuntu Source: https://xmake.io/zh/guide/quick-start.html Adds the official Xmake PPA to your Ubuntu system and installs Xmake. This ensures you get the latest versions. ```shell sudo add-apt-repository ppa:xmake-io/xmake sudo apt update sudo apt install xmake ``` -------------------------------- ### Compile and Install xmake with Make to a specific directory Source: https://xmake.io/zh/posts/quickstart-1-installation.html Installs xmake by compiling from source using Make, specifying a custom installation prefix. Requires root privileges. ```bash $ sudo make install prefix=/usr/local ``` -------------------------------- ### package:installdir Source: https://xmake.io/zh/api/scripts/package-instance.html Retrieves the installation directory for the package. It can also be used to get subdirectories within the installation path. If the specified directory does not exist, it will be created. ```APIDOC ## package:installdir ### Description * 获取包的安装目录。 也可用于获取子目录。 如果给定的目录树不存在,它将被创建。 ### Method lua package:installdir(...path: string) ### Parameters #### Path Parameters - **...path** (string) - Optional path to a subdirectory within the installation directory. ### Usage Example lua -- returns the installation directory package:installdir() -- returns the subdirectory include inside the installation directory package:installdir("include") -- returns the subdirectory include/files package:installdir("include", "files") ``` -------------------------------- ### Create a Qt QuickApp project Source: https://xmake.io/zh/posts/quickstart-2-create-and-build-project.html Create a Qt QuickApp project named 'test' by specifying C++ language (`-l c++`) and the `qt.quickapp` template (`-t qt.quickapp`). ```bash $ xmake create -l c++ -t qt.quickapp test create test ... [+]: xmake.lua [+]: src/interface.c [+]: src/main.qml [+]: src/interface.h [+]: src/test.c [+]: src/main.cpp [+]: src/qml.qrc [+]: .gitignore create ok! ``` -------------------------------- ### Add Component Installation to NSIS Source: https://xmake.io/zh/guide/extensions/builtin-plugins.html Extends NSIS installers with custom commands that execute only when a specific component is selected by the user. This example enables long path support. ```lua xpack("test") add_components("LongPath") xpack_component("LongPath") set_default(false) set_title("Enable Long Path") set_description("Increases the maximum path length limit, up to 32,767 characters (before 256).") on_installcmd(function (component, batchcmds) batchcmds:rawcmd("nsis", [[ ${If} $NoAdmin == "false" ; Enable long path WriteRegDWORD ${HKLM} "SYSTEM\CurrentControlSet\Control\FileSystem" "LongPathsEnabled" 1 ${EndIf}]]]) end) ``` -------------------------------- ### Define Custom Install Script for Binary Scheme Source: https://xmake.io/zh/posts/xmake-update-v3.0.7.html Use `scheme:set("install", ...)` within `on_source` to define scheme-specific installation logic, encapsulating it within the scheme definition. ```lua on_source(function (package) local binary = package:scheme("binary") binary:set("install", function (package) -- 二进制方案的自定义安装逻辑 os.cp(is_host("windows") and "ninja.exe" or "ninja", package:installdir("bin")) end) end) ``` -------------------------------- ### Complete Input Dialog Example Source: https://xmake.io/zh/api/scripts/extension-modules/core/ui/inputdialog.html A full example demonstrating the creation, configuration, button addition, and display of an input dialog within an application context. Requires importing 'core.ui.application' and 'core.ui.rect'. ```lua import("core.ui.inputdialog") import("core.ui.rect") import("core.ui.application") local app = application() function app:init() application.init(self, "demo") self:background_set("blue") -- 创建输入对话框 local dialog = inputdialog:new("input", rect{0, 0, 50, 10}) dialog:text():text_set("请输入您的姓名:") dialog:background_set(self:background()) dialog:frame():background_set("cyan") -- 添加按钮 dialog:button_add("yes", "< 是 >", function (v) local input = dialog:textedit():text() print("输入值:", input) dialog:quit() end) dialog:button_add("no", "< 否 >", function (v) dialog:quit() end) -- 显示对话框 dialog:show(false) -- 初始隐藏 -- 插入到应用程序 self:insert(dialog, {centerx = true, centery = true}) end function app:on_resize() self:dialog_input():bounds_set(rect{0, 0, 50, 10}) self:center(self:dialog_input(), {centerx = true, centery = true}) application.on_resize(self) end app:run() ``` -------------------------------- ### application:statusbar Source: https://xmake.io/zh/api/scripts/extension-modules/core/ui/application.html Gets the application's status bar. A complete custom application example. ```APIDOC ## application:statusbar ### Description Gets the application's status bar. ### API lua application:statusbar() ### Parameters No parameters. ### Returns - **statusbar**: Returns the status bar instance. ### Usage Access the status bar component, here is a complete custom application example: lua import("core.ui.log") import("core.ui.rect") import("core.ui.label") import("core.ui.event") import("core.ui.window") import("core.ui.application") local demo = application() function demo:init() application.init(self, "demo") self:background_set("blue") -- Create the main window local win = window:new("window.body", rect{1, 1, self:width() - 1, self:height() - 1}, "主窗口") self:insert(win) -- Create the status bar local statusbar = self:statusbar() statusbar:text_set("就绪") end function demo:on_resize() self:desktop():bounds_set(rect{0, 0, self:width(), self:height()}) application.on_resize(self) end function main(...) demo:run(...) end ``` -------------------------------- ### Basic on_install with Default Platform Support Source: https://xmake.io/zh/api/description/package-dependencies.html Use on_install without platform arguments to apply the installation script to all platforms. The script function receives the package object. ```lua on_install(function (package) -- TODO end) ``` -------------------------------- ### Example of starting and managing named threads Source: https://xmake.io/zh/api/scripts/extension-modules/core/base/thread.html Demonstrates how to start two named threads, each executing a callback function with an ID, and then waits for both threads to complete. It highlights thread isolation and parameter serialization. ```lua import("core.base.thread") function callback(id) import("core.base.thread") print("%s: %d starting ..", thread.running(), id) for i = 1, 10 do print("%s: %d", thread.running(), i) os.sleep(1000) end print("%s: %d end", thread.running(), id) end function main() local t0 = thread.start_named("thread_0", callback, 0) local t1 = thread.start_named("thread_1", callback, 1) t0:wait(-1) t1:wait(-1) end ``` -------------------------------- ### Build WDM Driver (Example 2) Source: https://xmake.io/zh/examples/cpp/wdk.html Configure and build another WDM driver, this time specifying tracewpp flags and handling MOF files. It also includes specific handling for a MOF header file. ```lua target("msdsm") add_rules("wdk.driver", "wdk.env.wdm") add_values("wdk.tracewpp.flags", "-func:TracePrint((LEVEL,FLAGS,MSG,...))") add_files("*.c", {rule = "wdk.tracewpp"}) add_files("*.rc", "*.inf") add_files("*.mof|msdsm.mof") add_files("msdsm.mof", {values = {wdk_mof_header = "msdsmwmi.h"}}) ``` -------------------------------- ### Configure Specific Installation Directories Source: https://xmake.io/zh/guide/basic-commands/install-and-uninstall.html Starting from v3.0.7, you can configure specific installation directories for binaries, libraries, and include files using options like --bindir, --libdir, and --includedir. ```sh xmake install -o /tmp/usr --bindir=mybin --libdir=mylib ``` -------------------------------- ### Install Android Qt Application with xmake Source: https://xmake.io/zh/posts/quickstart-6-build-qt-project.html After building, use the 'xmake install' command to deploy the generated Android application (APK) to a connected device or emulator. ```bash $ xmake install installing appdemo ... installing build/android/armv7-a/release/appdemo.apk .. success install ok! ``` -------------------------------- ### Define Package Test Script Source: https://xmake.io/zh/api/description/package-dependencies.html Use `on_test` to define a script that runs tests after a package is installed. If tests fail, the installation is rolled back. This example checks for C functions like `inflate` and includes. ```lua on_test(function (package) assert(package:has_cfuncs("inflate", {includes = "zlib.h"})) end) ``` -------------------------------- ### Using Zig Toolchain Source: https://xmake.io/zh/examples/configuration/remote_toolchain.html This example demonstrates how to integrate the Zig toolchain by adding it as a requirement and specifying it for a binary target. This is useful for projects written in Zig. ```lua add_rules("mode.debug", "mode.release") add_requires("zig") target("test") set_kind("binary") add_files("src/*.zig") set_toolchains("@zig") ``` -------------------------------- ### Get CPU Vendor ID Source: https://xmake.io/zh/api/scripts/extension-modules/core/base/cpu.html Retrieves the CPU vendor ID. Example: "GenuineIntel" or "AuthenticAMD". ```lua import("core.base.cpu") local vendor = cpu.vendor() print("CPU 厂商:", vendor) -- 输出: "GenuineIntel" 或 "AuthenticAMD" ``` -------------------------------- ### Define and Switch Installation Schemes Source: https://xmake.io/zh/guide/best-practices/package-spec.html Use `add_schemes` to declare different installation methods (e.g., 'binary' for prebuilt, 'source' for building from source). The `on_install` hook can then use `package:current_scheme()` to apply the correct logic. Fallback to `package:data("scheme")` for compatibility. ```lua add_schemes("binary", "source") on_install(function (package) local scheme = package:current_scheme() or package:data("scheme") if scheme == "binary" then -- install prebuilt artifacts else -- build from source end end) ``` -------------------------------- ### Build Package with Meson Source: https://xmake.io/zh/api/scripts/extension-modules/package/tools.html Builds a package using Meson, performing setup and compilation. This is useful when only building is required, without installation. ```lua on_install(function (package) import("package.tools.meson").build(package, {"-Ddefault_library=static"}) end) ``` -------------------------------- ### Build WDM Driver (Example 1) Source: https://xmake.io/zh/examples/cpp/wdk.html Configure and build a WDM (Windows Driver Model) driver. This example specifies WDM rules and customizes man flags and resources. ```lua target("kcs") add_rules("wdk.driver", "wdk.env.wdm") add_values("wdk.man.flags", "-prefix Kcs") add_values("wdk.man.resource", "kcsCounters.rc") add_values("wdk.man.header", "kcsCounters.h") add_values("wdk.man.counter_header", "kcsCounters_counters.h") add_files("*.c", "*.rc", "*.man") ``` -------------------------------- ### Get Source Kind of a File Source: https://xmake.io/zh/api/scripts/extension-modules/core/language/language.html Determines the source kind of a given file path. Returns the source kind string (e.g., 'cxx', 'cc') or nil if the file type is not recognized. The example shows how to get the source kind for a '.cpp' file. ```lua print(language.sourcekind_of("/xxxx/test.cpp")) ``` -------------------------------- ### Full menubar usage example Source: https://xmake.io/zh/api/scripts/extension-modules/core/ui/menubar.html A comprehensive example demonstrating the creation and integration of a menubar within an application, including window management and event handling for resizing. Requires 'core.ui.menubar', 'core.ui.window', 'core.ui.rect', and 'core.ui.application' modules. ```lua import("core.ui.menubar") import("core.ui.window") import("core.ui.rect") import("core.ui.application") local demo = application() function demo:init() application.init(self, "demo") self:background_set("blue") -- 创建菜单栏 local menubar = menubar:new("menubar", rect{1, 1, self:width() - 1, 1}) menubar:title():text_set("Xmake Demo Application") menubar:title():textattr_set("red bold") -- 创建主窗口 local win = window:new("main", rect{1, 2, self:width() - 1, self:height() - 2}, "主窗口") -- 添加到应用程序 self:insert(menubar) self:insert(win) self._menubar = menubar self._win = win end function demo:on_resize() self._menubar:bounds_set(rect{1, 1, self:width() - 1, 1}) self._win:bounds_set(rect{1, 2, self:width() - 1, self:height() - 2}) application.on_resize(self) end function main(...) demo:run(...) end ``` -------------------------------- ### Conan Build Execution Example Source: https://xmake.io/zh/guide/package-management/using-third-party-packages.html This output shows the compilation process after executing `xmake`, including the confirmation prompt for installing Conan packages. ```sh ruki:test_package ruki$ xmake checking for the architecture ... x86_64 checking for the Xcode directory ... /Applications/Xcode.app checking for the SDK version of Xcode ... 10.14 note: try installing these packages (pass -y to skip confirm)? -> conan::zlib/1.2.11 (debug) -> conan::openssl/1.1.1g please input: y (y/n) => installing conan::zlib/1.2.11 .. ok => installing conan::openssl/1.1.1g .. ok [ 0%]: cache compiling.release src/main.c [100%]: linking.release test ``` -------------------------------- ### on_install Source: https://xmake.io/zh/api/description/custom-rule.html Custom install script for rules. ```APIDOC ## on_install ### Description Custom install script for rules. This function overrides the default install behavior of the applied target. ### Function Signature API lua ``` on_install(script: ) ``` ### Parameters - **script** (function) - The install script function, which takes a target as a parameter. ### Usage Example ```lua rule("markdown") on_install(function (target) end) ``` ``` -------------------------------- ### Search Packages in xmake-repo Source: https://xmake.io/zh/posts/xmake-update-v2.5.5.html Use `xrepo search` to find packages within the xmake-repo. This example searches for 'zlib' and packages starting with 'pcr*'. ```console $ xrepo search zlib "pcr*" zlib: -> zlib: A Massively Spiffy Yet Delicately Unobtrusive Compression Library (in xmake-repo) pcr*: -> pcre2: A Perl Compatible Regular Expressions Library (in xmake-repo) -> pcre: A Perl Compatible Regular Expressions Library (in xmake-repo) ``` -------------------------------- ### on_install for Specific Platforms and Architectures Source: https://xmake.io/zh/api/description/package-dependencies.html Define platform and architecture combinations, such as 'linux|x86_64' and 'iphoneos|arm64', to target specific build environments. ```lua on_install("linux|x86_64", "iphoneos|arm64", function (package) -- TODO end) ``` -------------------------------- ### Simplified Toolchain Configuration Examples in xmake Source: https://xmake.io/zh/posts/xmake-update-v3.0.5.html Provides examples of simplified toolchain configurations in xmake, including simple toolchains, toolchains with packages, and toolchains with configurations and packages. ```lua -- 简单工具链 set_toolchains("clang") -- 带包的工具链 set_toolchains("clang@llvm-10") set_toolchains("@muslcc") set_toolchains("zig") -- 带配置和包的工具链 set_toolchains("mingw[clang]@llvm-mingw") set_toolchains("msvc[vs=2025]") -- 多个配置 set_toolchains("mingw[clang]", {sdk = "/path/to/llvm-mingw"}) ``` -------------------------------- ### Get Package Build Hash Source: https://xmake.io/zh/api/scripts/package-instance.html Retrieves the unique build hash for the package. This ensures that packages with different configurations are installed in distinct paths. ```lua package:buildhash() ``` -------------------------------- ### Generate Meson Build Files Source: https://xmake.io/zh/api/scripts/extension-modules/package/tools.html Generates Meson build files (setup phase) without compiling or installing. This is useful for preparing the build environment. ```lua on_install(function (package) import("package.tools.meson").generate(package, {"-Dbuildtype=release"}) end) ``` -------------------------------- ### Install Precompiled Binaries Source: https://xmake.io/zh/guide/best-practices/package-spec.html Strictly classify and move artifacts to standard subdirectories of `package:installdir()` during the `on_install` phase. Use `os.cp` for cross-platform files. ```lua os.cp("include/*", package:installdir("include")) os.cp("lib/*.a", package:installdir("lib")) os.cp("bin/*", package:installdir("bin")) ``` -------------------------------- ### add_requires - Installing Third-Party Packages Source: https://xmake.io/zh/api/description/global-interfaces.html Demonstrates how to install packages from various third-party package managers like Conan, Conda, Vcpkg, Homebrew, Pacman, Apt, Clib, Dub, and Portage using the add_requires function. It shows examples of specifying package versions, aliases, and configurations. ```APIDOC ## add_requires - Installing Third-Party Packages This section details how to install packages from various third-party package managers using the `add_requires` function. ### Supported Package Managers: - Conan (e.g., `conan::openssl/1.1.1g`) - Conda (e.g., `conda::libpng 1.3.67`) - Vcpkg (e.g., `vcpkg::ffmpeg`) - Homebrew/Linuxbrew (e.g., `brew::pcre2/libpcre2-8`) - Pacman on archlinux/msys2 (e.g., `pacman::libcurl`) - Apt on ubuntu/debian (e.g., `apt::zlib1g-dev`) - Clib (e.g., `clib::clibs/bytes@0.0.4`) - Dub (e.g., `dub::log 0.4.3`) - Portage on Gentoo/Linux (e.g., `portage::libhandy`) ### Example Usage: ```lua add_requires("conan::zlib/1.2.11", {alias = "zlib", debug = true}) add_requires("conan::openssl/1.1.1g", {alias = "openssl", configs = {options = "OpenSSL:shared=True"}}) target("test") set_kind("binary") add_files("src/*.c") add_packages("openssl", "zlib") ``` This example shows how to add `zlib` and `openssl` packages from Conan, with `zlib` aliased and set to debug mode, and `openssl` configured for shared library usage. The `target` block then adds these packages to the build target. ``` -------------------------------- ### Build and Install Qt Application for Android Source: https://xmake.io/zh/examples/cpp/graphics/qt.html Create a Qt QuickApp for Android and build it into an APK. Use `xmake install` to deploy the APK to a connected device. ```sh $ xmake create -t quickapp_qt -l c++ appdemo $ cd appdemo $ xmake f -p android --ndk=~/Downloads/android-ndk-r19c/ --android_sdk=~/Library/Android/sdk/ -c $ xmake [ 0%]: compiling.qt.qrc src/qml.qrc [ 50%]: cache compiling.release src/main.cpp [100%]: linking.release libappdemo.so [100%]: generating.qt.app appdemo.apk $ xmake install installing appdemo ... installing build/android/release/appdemo.apk .. Success install ok!👌 ``` -------------------------------- ### Using Packages from Third-Party Repositories (Homebrew) Source: https://xmake.io/zh/guide/package-management/using-packages-in-cmake.html Example of using `xrepo_package` to install a package ('gflags') from the Homebrew package manager by prefixing the package name with 'brew::'. ```APIDOC ## Using Packages from Third-Party Repositories (Homebrew) ### Description Installs the 'gflags' package from the Homebrew package manager using the `brew::` namespace prefix. ### Code Example ```cmake xrepo_package("brew::gflags") ``` ``` -------------------------------- ### Display Help for Custom Option Source: https://xmake.io/zh/posts/custom-option.html Run `xmake f --help` to view the custom option 'hello' in the displayed menu, along with its description and default value. ```bash $ xmake f --help ``` -------------------------------- ### Using Packages from Third-Party Repositories (Vcpkg) Source: https://xmake.io/zh/guide/package-management/using-packages-in-cmake.html Example of using `xrepo_package` to install a package ('gflags') from the Vcpkg package manager by prefixing the package name with 'vcpkg::'. ```APIDOC ## Using Packages from Third-Party Repositories (Vcpkg) ### Description Installs the 'gflags' package from the Vcpkg package manager using the `vcpkg::` namespace prefix. ### Code Example ```cmake xrepo_package("vcpkg::gflags") ``` ``` -------------------------------- ### Client Configuration Example Source: https://xmake.io/zh/guide/extras/build-cache.html Example of the `client.conf` file, specifying the server address and token for the remote cache connection. ```json { "remote_cache" = { "connect" = "127.0.0.1:9692, "token" = "590234653af52e91b9e438ed860f1a2b" } } } ``` -------------------------------- ### Using Packages from Third-Party Repositories (Conda) Source: https://xmake.io/zh/guide/package-management/using-packages-in-cmake.html Example of using `xrepo_package` to install a package ('gflags') from the Conda package manager by prefixing the package name with 'conda::'. ```APIDOC ## Using Packages from Third-Party Repositories (Conda) ### Description Installs the 'gflags' package version 2.2.2 from the Conda package manager using the `conda::` namespace prefix. ### Code Example ```cmake xrepo_package("conda::gflags 2.2.2") ``` ``` -------------------------------- ### Build and Run Qt Quick Application Source: https://xmake.io/zh/examples/cpp/graphics/qt.html Compile and run a Qt Quick application using xmake. xmake typically auto-detects the Qt SDK if installed in a standard location. ```sh $ xmake checking for the architecture ... x86_64 checking for the Xcode directory ... /Applications/Xcode.app checking for the SDK version of Xcode ... 10.15 checking for the Qt SDK directory ... /Users/ruki/Qt5.13.2/5.13.2/clang_64 checking for the Qt SDK version ... 5.13.2 [ 0%]: cache compiling.release src/main.cpp [ 49%]: compiling.qt.qrc src/qml.qrc [100%]: linking.release test build ok! $ xmake run ``` -------------------------------- ### Using Packages from Third-Party Repositories (Conan) Source: https://xmake.io/zh/guide/package-management/using-packages-in-cmake.html Example of using `xrepo_package` to install a package ('gflags') from the Conan package manager by prefixing the package name with 'conan::'. ```APIDOC ## Using Packages from Third-Party Repositories (Conan) ### Description Installs the 'gflags' package version 2.2.2 from the Conan package manager using the `conan::` namespace prefix. ### Code Example ```cmake xrepo_package("conan::gflags/2.2.2") ``` ``` -------------------------------- ### Build and Run Swift-C++ Interoperability Example Source: https://xmake.io/zh/posts/xmake-update-v3.0.5.html Build the project using 'xmake' and run the resulting binary to see the Swift function called from C++. ```bash $ xmake checking for platform ... macosx checking for architecture ... x86_64 checking for Xcode directory ... /Applications/Xcode.app [ 3%]: generating.swift.header fibonacci-Swift.h [ 38%]: cache compiling.release src/fibonacci.cpp [ 56%]: compiling.release lib/fibonacci/fibonacci.swift [ 76%]: linking.release cxx_interop [100%]: build ok, spent 1.785s $ xmake run x [swift]: 5 x [swift]: 4 ... 8 ``` -------------------------------- ### Full window UI example Source: https://xmake.io/zh/api/scripts/extension-modules/core/ui/window.html A comprehensive example demonstrating the creation of a window with a title and shadow, adding labels to its content panel, and handling window resizing. This showcases the integration of multiple UI components within a terminal application. ```lua import("core.ui.window") import("core.ui.label") import("core.ui.rect") import("core.ui.application") local demo = application() function demo:init() application.init(self, "demo") self:background_set("blue") -- 创建带标题和阴影的主窗口 local win = window:new("main", rect{1, 1, self:width() - 1, self:height() - 1}, "主窗口", true) -- 向面板添加内容 local panel = win:panel() panel:insert(label:new("label1", rect{2, 2, 30, 1}, "欢迎使用终端 UI!")) panel:insert(label:new("label2", rect{2, 4, 30, 1}, "这是一个窗口示例。")) panel:insert(label:new("label3", rect{2, 6, 30, 1}, "Tab 键在视图之间导航。")) self:insert(win) self._win = win end function demo:on_resize() self._win:bounds_set(rect{1, 1, self:width() - 1, self:height() - 1}) application.on_resize(self) end function main(...) demo:run(...) end ``` -------------------------------- ### Set dialog background color Source: https://xmake.io/zh/api/scripts/extension-modules/core/ui/dialog.html Configure the background color of the dialog. This example demonstrates a full application setup including dialog creation and event handling. ```lua import("core.ui.log") import("core.ui.rect") import("core.ui.label") import("core.ui.event") import("core.ui.boxdialog") import("core.ui.textdialog") import("core.ui.inputdialog") import("core.ui.application") local demo = application() function demo:init() application.init(self, "demo") self:background_set("blue") -- 创建主对话框 local dialog_main = boxdialog:new("dialog.main", rect{1, 1, self:width() - 1, self:height() - 1}, "主对话框") dialog_main:text():text_set("示例对话框内容") dialog_main:button_add("ok", "< 确定 >", function (v) self:quit() end) dialog_main:button_add("cancel", "< 取消 >", "cm_quit") self:insert(dialog_main) end function demo:on_resize() self:dialog_main():bounds_set(rect{1, 1, self:width() - 1, self:height() - 1}) application.on_resize(self) end function main(...) demo:run(...) end ``` -------------------------------- ### Find Package with CMake (LibXml2) Source: https://xmake.io/zh/guide/package-management/using-local-packages.html This example shows how to use `xmake l find_package` to get information about the LibXml2 library using CMake's `find_package` mechanism. ```sh $ xmake l find_package cmake::LibXml2 { links = { "xml2" }, includedirs = { "/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/libxml2" }, linkdirs = { "/usr/lib" } } ```