GN (Generate Ninja) 是一个用于生成 Ninja 构建文件的元构建系统,主要用于 Chromium 项目。以下是 GN 的详细使用教程,包括安装、基本操作、配置、常见问题和高级用法。
安装 GN
方法一:通过 depot_tools
安装
- 安装依赖工具:
确保已安装 Python 2.7+ 和 Ninja 编译器。 - 获取
depot_tools
并配置路径:
git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git
export PATH=$PATH:/path/to/depot_tools
- 确保
depot_tools
已正确配置:
which gn
方法二:从源代码编译 GN
- 获取 GN 源码:
git clone https://gn.googlesource.com/gn
cd gn
- 编译 GN:
python build/gen.py
ninja -C out
- 将 GN 添加到 PATH:
export PATH=$PATH:/path/to/gn/out
方法三:通过预编译二进制文件安装 GN
- 下载预编译二进制文件:
从以下链接下载适用于您操作系统的预编译 GN 二进制文件:
- 将二进制文件解压并添加到 PATH:
mkdir -p ~/bin
mv gn ~/bin/gn
chmod +x ~/bin/gn
export PATH=$PATH:~/bin
方法四:通过包管理器安装 GN
- 在 macOS 上使用 Homebrew 安装 GN:
brew install gn
- 在 Linux 上使用包管理器安装 GN:
对于基于 Debian 的系统:
sudo apt-get install gn
快速入门
- 创建项目目录:
mkdir my_project && cd my_project
- 创建
BUILD.gn
文件:
executable("hello_world") {
sources = [ "hello_world.cc" ]
}
- 生成构建文件:
gn gen out/Default
- 编译项目:
ninja -C out/Default
配置和编译参数
- 配置
args.gn
文件:
gn args out/Default
在文件中添加配置项:
is_debug = true
target_os = "mac"
target_cpu = "x64"
- 查看和修改参数:
gn args out/Default --list
该命令显示所有可配置的构建参数及其默认值和说明。
跨编译
- 配置跨编译参数:
在args.gn
文件中添加:
target_os = "linux"
target_cpu = "arm"
- 生成跨编译文件:
gn gen out/CrossCompile
- 编译跨平台项目:
ninja -C out/CrossCompile
常见问题
- GN 文件语法:
-
- 注释:使用
#
进行注释。 - 变量:使用
=
赋值。 - 函数:调用函数执行操作。
- 注释:使用
- 调试 GN 配置:
-
- 使用
gn help
获取命令帮助。 - 使用
gn desc
查看目标描述。
- 使用
- 常见错误:
-
- 文件未找到:检查
sources
路径。 - 编译失败:确保
args.gn
配置正确。
- 文件未找到:检查
高级用法
- 自定义目标:
static_library("mylib") {
sources = [ "mylib.cc" ]
}
- 条件语句:
if (is_debug) {
defines = [ "DEBUG" ]
} else {
defines = [ "RELEASE" ]
}
- 模板:
template("my_template") {
sources = [ "$1.cc" ]
}
my_template("example") {
sources = [ "example" ]
}
GN 文件详解
BUILD.gn 文件
BUILD.gn
文件是 GN 的构建脚本,定义了构建目标和依赖关系。常见的构建目标包括 executable
、shared_library
、static_library
等。
示例:
executable("my_executable") {
sources = [ "main.cc", "util.cc" ]
deps = [ ":my_library" ]
}
static_library("my_library") {
sources = [ "lib.cc", "lib_util.cc" ]
}
args.gn 文件
args.gn
文件用于配置构建参数,例如目标平台、编译模式等。
示例:
is_debug = false
target_cpu = "arm64"
use_libfoo = true
.gn 文件
.gn
文件是 GN 项目的配置文件,通常位于项目根目录,用于设置默认构建目录和目标。
示例:
buildconfig = "//build/config/BUILDCONFIG.gn"
GN 高级功能
自定义工具链
GN 支持自定义工具链,用于跨编译或使用特定的编译器。
示例:
toolchain("my_toolchain") {
tool("cc") {
command = "gcc -c $in -o $out"
}
tool("cxx") {
command = "g++ -c $in -o $out"
}
}
模板
模板用于定义可复用的构建规则。
示例:
template("my_template") {
action("${target_name}") {
script = "do_something.py"
sources = [ "input.txt" ]
outputs = [ "output.txt" ]
}
}
my_template("example") {
sources = [ "example.txt" ]
}
参考资料
本主页会定期更新,为了能够及时获得更新,敬请关注我:点击左下角的关注。也可以关注公众号:请在微信上搜索公众号“AI与编程之窗”并关注,或者扫描以下公众号二维码关注,以便在内容更新时直接向您推送。