1
2## Bazel、Soong、GN构建规则对比
3| 规则 | bazel | android.bp | gn | openharmony高级模板 |
4| --- | --- | --- | --- | --- |
5| 可执行文件 | cc_binary | cc_binary | executable | ohos_executable |
6| 静态库 | cc_library(linkstatic=1) | cc_library_static | static_library | ohos_static_library |
7| 动态库 | cc_shared_library | cc_library_shared | shared_library | ohos_shared_library |
8| 目标名 | name | name | target_name |  |
9| 依赖 | deps | shared_libs、static_libs | deps |  |
10| 源码文件 | srcs | src | sources |  |
11| 编译选项 | copts | cflags, cppflags | cflags, ccflags |  |
12| 宏定义 | defines | cflags = [ "-DXXX" ] | defines |  |
13| 头文件路径 | includes | include_dirs | include_dirs |  |
14| 链接选项 | linkopts | ldflags | ldflags |  |
15
16## 构建示例
17源码文件为main.cpp,动态库和静态库的源码文件为lib.cpp, 使用下面文件,将分别生成一个可执行文件hello_world,一个动态库libhello.so和一个静态库libhello.a18### Bazel:
19在项目的根目录下创建一个名为BUILD的文件,内容如下:
20```go
21cc_library(
22    name = "hello_lib",
23    srcs = ["lib.cpp"],
24    hdrs = ["lib.h"],
25    linkstatic=1
26)
27cc_shared_library(
28    name = "hello_shlib",
29    srcs = ["lib.cpp"],
30    hdrs = ["lib.h"],
31)
32cc_binary(
33    name = "hello_world",
34    srcs = ["main.cpp"],
35    deps = [":hello_lib",":hello_shlib"],
36)
37```
38### Android.bp39创建一个名为Android.bp的文件,内容如下:
40```go
41cc_library_shared {
42    name: "libhello",
43    srcs: ["lib.cpp"],
44}
45
46cc_library_static {
47    name: "libhello_static",
48    srcs: ["lib.cpp"],
49}
50
51cc_binary {
52    name: "hello_world",
53    srcs: ["main.cpp"],
54    shared_libs: ["libhello"],
55    static_libs: ["libhello_static"],
56}
57```
58
59### Android.mk60创建一个名为Android.mk的文件,内容如下:
61```makefile
62LOCAL_PATH := $(call my-dir)
63
64include $(CLEAR_VARS)
65
66LOCAL_MODULE    := libhello
67LOCAL_SRC_FILES := lib.cpp
68
69include $(BUILD_SHARED_LIBRARY)
70
71include $(CLEAR_VARS)
72
73LOCAL_MODULE    := libhello_static
74LOCAL_SRC_FILES := lib.cpp
75
76include $(BUILD_STATIC_LIBRARY)
77
78include $(CLEAR_VARS)
79
80LOCAL_MODULE    := hello_world
81LOCAL_SRC_FILES := main.cpp
82LOCAL_SHARED_LIBRARIES := libhello
83LOCAL_STATIC_LIBRARIES := libhello_static
84
85include $(BUILD_EXECUTABLE)
86```
87
88### GN:
89创建一个名为BUILD.gn的文件,内容如下:
90```go
91shared_library("libhello") {
92  sources = [ "lib.cpp" ]
93}
94
95static_library("libhello_static") {
96  sources = [ "lib.cpp" ]
97}
98
99executable("hello_world") {
100  sources = [ "main.cpp" ]
101  deps = [ ":libhello", ":libhello_static" ]
102}
103```
104
105
106