Javascript Engine V8 Embedding - 编译

直接 git pull V8 的代码是不行的,需要使用 Google 提供的 depot_tools 工具包来获对代码并配置。

由于要从 Google 下载资源,需要科学上网,下载和编译的耗时都较长,分别视你的网络情况和机器配置而定。

为了屏蔽掉不同系统的差异,直接使用 Docker 容器环境来编译。

编译

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
docker run -it ubuntu bash  

# 安装必要的工具
apt update
apt install -y git curl python xz-utils lbzip2 lsb-release lsb-core sudo vim

# 安装 Google 开发工具包
# see more: https://v8.dev/docs/source-code#using-git
cd /root && git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git

export PATH=$PATH:/root/depot_tools

gclient

# 下载 v8 代码
fetch v8
cd v8

git checkout refs/tags/7.1.11 -b sample -t

# 同步依赖
gclient sync

# 创建一个构建配置
tools/dev/v8gen.py x64.release.sample

# 开始构建 v8 静态库
# 构建耗时较长,视你的机器配置而定
ninja -C out.gn/x64.release.sample v8_monolith

使用静态库

等上面 v8 编译完成后,就可以使用编译好的静态库了,我们编译一下 v8 提供的 hello-world 示例:

1
2
3
4
5
6
7
# 编译
g++ -I. -Iinclude samples/hello-world.cc -o hello_world -lv8_monolith -Lout.gn/x64.release.sample/obj/ -pthread -std=c++0x

# icu 数据文件,运行时需要
cp out.gn/x64.release.sample/icudtl.dat .

./hello_world

参考链接

https://v8.dev/docs/embed

https://v8.dev/docs/source-code#using-git