最近在整鸿蒙,它是用gn构建的,所以根据gn工程中的快速入门GN Quick Start guide做了个简单的实操,并做了下记录,[更改的工程放到的csdn上](https://download.youkuaiyun.com/download/gkxg001/90076533)
,分享出来,方便我后续查看哈哈哈哈。
安装
可以直接命令行的方式运行
ubuntu安装命令:
sudo apt install generate-ninja
建立构建目录
在构建的目录中进行操作后就无需再重新运行gn了,它会自动构建。构建需要基于相关的配置文件(.gn)的,所以构建时需要写好,但构建过程不会对源码(.c/.cpp等)进行校验。
- 构建命令
gn gen out
下面是将源码中的simple_build案例的.gn文件复制过来的。此时便可实现构建,当然在用ninja编译时肯定会报错。
首先根据这几个必要的构建文件来感受一下构建的方式:
.gn文件
# The location of the build configuration file.
buildconfig = "//build/BUILDCONFIG.gn"
指定gn配置文件
注:由于github中给的gn文件的说明链接国内正常手段访问不了,所以就直接大模型搜了下,结果为以下内容:
- 构建配置指定:通过
buildconfig
变量来指定构建配置文件的位置。例如,buildconfig = "//build/buildconfig.gn"
表示构建配置文件位于项目的build/buildconfig.gn
路径下。这使得GN工具能够识别项目的源根目录,并找到构建所需的配置信息。 - 全局变量和设置:虽然“.gn”文件本身可能不直接包含大量的构建规则或源文件列表,但它可以定义一些全局变量或设置,这些变量或设置可以在整个构建过程中被引用或修改。
- 依赖关系管理(间接):虽然具体的依赖关系通常在各个模块的
.gn
文件中定义,但根目录的“.gn”文件可以通过包含或引用其他配置文件来间接管理这些依赖关系。
./build/BUILDCONFIG.gn文件说明
if (target_os == "") {
target_os = host_os
}
.....
is_linux = host_os == "linux" && current_os == "linux" && target_os == "linux" #如果执行构建命令的操作系统、GN正在为其生成构建文件的当前操作系统环境(或相关变量所指的操作系统),以及最终生成的二进制文件或库将要运行的操作系统都是Linux,那么is_linux变量将被设置为真(true)
is_mac = host_os == "mac" && current_os == "mac" && target_os == "mac"
# All binary targets will get this list of configs by default.
# 配置编译的一些配置,compiler_defaults选项为/build/BUILD.gn文件目录下定义的
_shared_binary_target_configs = [ "//build:compiler_defaults" ]
# Apply that default list to the binary target types.
set_defaults("executable") {
configs = _shared_binary_target_configs
# Executables get this additional configuration.
# 配置编译的一些配置,executable_ldconfig选项为/build/BUILD.gn文件目录下定义的
configs += [ "//build:executable_ldconfig" ]
}
set_defaults("static_library") {
# 表示这些默认配置将应用于所有静态库目标
configs = _shared_binary_target_configs
}
.......
set_default_toolchain("//build/toolchain:gcc") #设置交叉编译链
./build/BUILD.gn文件说明
config("compiler_defaults") {
if (current_os == "linux") {
# 如果是linux系统编译器需要配置的选项如下
cflags = [
"-fPIC",
"-pthread",
]
}
}
config("executable_ldconfig") {
if (!is_mac) {
ldflags = [
"-Wl,-rpath=\$ORIGIN/",
"-Wl,-rpath-link=",
]
}
}
./build/toolchain/BUILD.gn文件说明
toolchain("gcc") {
tool("cc") {
depfile = "{
{output}}.d"
command = "gcc -MMD -MF $depfile {
{defines}} {
{include_dirs}} {
{cflags}} {
{cflags_c}} -c {
{source}} -o {
{output}}"
depsformat = "gcc"
description = "CC {
{output}}"
outputs =
[ "{
{source_out_dir}}/{
{target_output_name}}.{
{source_name_part}}.o" ]
}
...... # 省略
command = "g++ -shared {
{ldflags}} -o $sofile $os_specific_option @$rspfile"
description = "SOLINK $soname"
# Use this for {
{
output_extension}} expansions unless a target manually
# overrides it (in which case {
{
output_extension}} will be what the target
# specifies