Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Xmake
https://xmake.io/zh/
Admin
Xmake是一个基于Lua的轻量级跨平台自动构建工具,它提供简单快速的语法、强大的功能和友好的包管理整合,支持C/C++等多种语言的现代化构建。
Tokens:
720,145
Snippets:
7,998
Trust Score:
5.2
Update:
2 months ago
Context
Chat
Benchmark
64
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### XPack Configuration Example Source: https://xmake.io/zh/guide/extensions/builtin-plugins.html A comprehensive example of configuring XPack to generate multiple installer formats for a binary target. ```lua set_version("1.0.0") add_rules("mode.debug", "mode.release") includes("@builtin/xpack") target("test") set_kind("binary") add_files("src/*.cpp") xpack("test") set_formats("nsis", "zip", "targz", "runself") set_title("hello") set_author("ruki") set_description("A test installer.") set_homepage("https://xmake.io") set_licensefile("LICENSE.md") add_targets("test") add_installfiles("src/(assets/*.png)", {prefixdir = "images"}) add_sourcefiles("(src/**)") set_iconfile("src/assets/xmake.ico") after_installcmd(function (package, batchcmds) batchcmds:mkdir(package:installdir("resources")) batchcmds:cp("src/assets/*.txt", package:installdir("resources"), {rootdir = "src"}) batchcmds:mkdir(package:installdir("stub")) end) after_uninstallcmd(function (package, batchcmds) batchcmds:rmdir(package:installdir("resources")) batchcmds:rmdir(package:installdir("stub")) end) ``` -------------------------------- ### Usage examples for add_installfiles Source: https://xmake.io/zh/api/description/xpack-interfaces.html Examples showing basic file installation, subdirectory mapping, directory structure extraction, and variable expansion. ```lua xpack("test") add_installfiles("src/*.h") add_installfiles("doc/*.md") ``` ```lua xpack("test") add_installfiles("src/*.h", {prefixdir = "include"}) add_installfiles("doc/*.md", {prefixdir = "share/doc"}) ``` ```lua xpack("test") add_installfiles("src/(tbox/*.h)", {prefixdir = "include"}) add_installfiles("doc/(tbox/*.md)", {prefixdir = "share/doc"}) ``` ```lua xpack("test") set_version("1.0.0") add_installfiles("$(projectdir)/assets/(**.png)", {prefixdir = "share"}) add_installfiles("$(builddir)/test-$(version).txt") ``` -------------------------------- ### 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] ``` -------------------------------- ### Usage example for before_installcmd Source: https://xmake.io/zh/api/description/xpack-interfaces.html Adding custom installation commands to the batch command list. ```lua xpack("test") before_installcmd(function (package, batchcmds) batchcmds:mkdir(package:installdir("resources")) batchcmds:cp("src/assets/*.txt", package:installdir("resources"), {rootdir = "src"}) batchcmds:mkdir(package:installdir("stub")) end) ``` -------------------------------- ### 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() ``` -------------------------------- ### 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.") ``` -------------------------------- ### Runself Packaging Output Source: https://xmake.io/zh/guide/extensions/builtin-plugins.html Example output for generating a runself installer. ```sh $ xmake pack packing build/xpack/test/test-macosx-src-v1.0.0.gz.run pack ok ``` ```sh $ sh ./build/xpack/test/test-macosx-src-v1.0.0.gz.run ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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: <package>, configs: <table>, opt: <table>)` ### 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. ``` -------------------------------- ### on_install Source: https://xmake.io/zh/api/description/custom-rule.html Defines a custom installation script that overrides default target installation behavior. ```APIDOC ## on_install(script) ### Description Defines a custom installation script that overrides the default installation behavior of the applied target. ### Parameters - **script** (function(target)) - Required - The installation script function receiving the target object. ``` -------------------------------- ### Configure Runself Installer Source: https://xmake.io/zh/guide/extensions/builtin-plugins.html Configure a shell-based self-extracting installer with custom installation logic. ```lua xpack("test") set_formats("runself") add_sourcefiles("(src/**)") on_installcmd(function (package, batchcmds) batchcmds:runv("make", {"install"}) end) ``` -------------------------------- ### 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() ``` -------------------------------- ### 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" } } ``` -------------------------------- ### 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 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 ``` -------------------------------- ### Define custom installation command Source: https://xmake.io/zh/guide/extensions/builtin-plugins.html Configures a custom installation script using on_installcmd. ```lua on_installcmd(function (package, batchcmds) batchcmds:runv("./scripts/get.sh", {"__local__"}) 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) ``` -------------------------------- ### Complete link order configuration example Source: https://xmake.io/zh/api/description/project-target.html A comprehensive example demonstrating rules, dependencies, packages, link groups, and link orders in a target configuration. ```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}) ``` -------------------------------- ### 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") ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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" } } } } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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") ``` -------------------------------- ### 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 ``` -------------------------------- ### NSIS Packaging Output Source: https://xmake.io/zh/guide/extensions/builtin-plugins.html Example output when running the pack command for an NSIS installer. ```sh $ xmake pack note: install or modify (m) these packages (pass -y to skip confirm)? in xmake-repo: -> nsis 3.09 please input: y (y/n/m) => install nsis 3.09 .. ok [ 25%]: compiling.release src\main.cpp [ 37%]: compiling.release src\main.cpp [ 50%]: linking.release foo.dll [ 62%]: linking.release test.exe packing build\xpack\test\test-windows-x64-v1.0.0.exe pack ok ``` -------------------------------- ### 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! ``` -------------------------------- ### Get Program Directory Source: https://xmake.io/zh/api/scripts/builtin-modules/os.html Retrieves the directory where the Xmake main program scripts are installed. ```lua os.programdir() ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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) ``` -------------------------------- ### 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") ``` -------------------------------- ### Advanced Runself Configuration Source: https://xmake.io/zh/guide/extensions/builtin-plugins.html A complex example of configuring a runself installer that includes git repository cleanup and source file selection. ```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.directory(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) ``` -------------------------------- ### Usage example for before_package Source: https://xmake.io/zh/api/description/xpack-interfaces.html Configuring custom scripts to run before packaging. ```lua xpack("test") before_package(function (package) -- TODO end) ``` -------------------------------- ### 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) ``` -------------------------------- ### 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" ``` -------------------------------- ### 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") ``` -------------------------------- ### 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) ``` -------------------------------- ### 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 ``` -------------------------------- ### 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) ``` -------------------------------- ### 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) ``` -------------------------------- ### 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"}) ``` -------------------------------- ### 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")) ``` -------------------------------- ### 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) ``` -------------------------------- ### 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!👌 ``` -------------------------------- ### 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. ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 (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") ``` ``` -------------------------------- ### 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 (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") ``` ``` -------------------------------- ### 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 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%]: <cxx_interop> 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 ```