我用rust的cargo build命令编译polars-cli时,用时达到14分钟,如下所示。
Finished `dev` profile [unoptimized + debuginfo] target(s) in 14m 19s,
通过核对时间戳,发觉其中最后一步生成可执行文件花了6分钟。
于是向DeepSeek请教,我在编译polars-cli时,debug 总用时14分钟,最后一步生成可执行文件花了6分钟,有办法缩短吗?
他向我推荐了mold(现代链接器),它的主页是https://github.com/rui314/mold,
关于rust它这么说
If you are using Rust
Create .cargo/config.toml in your project directory with the following:
[target.‘cfg(target_os = “linux”)’]
linker = “clang”
rustflags = [“-C”, “link-arg=-fuse-ld=/path/to/mold”]
where /path/to/mold is an absolute path to the mold executable. In the example above, we use clang as a linker driver since it always accepts the -fuse-ld option. If your GCC is recent enough to recognize the option, you may be able to remove the linker = “clang” line.
[target.‘cfg(target_os = “linux”)’]
rustflags = [“-C”, “link-arg=-fuse-ld=mold”]
If you want to use mold for all projects, add the above snippet to ~/.cargo/config.toml.
我的gcc版本12.2足够新,把上述两行添加到/usr/local/cargo/config.toml,但是cargo build报错:
= note: cc: error: unrecognized command-line option '-fuse-ld=/par/mold240/bin/mold'
再问deepseek, 得到了答案,原来gcc不支持绝对路径,而我用上述clang的语法加了绝对路径。所以要把mold二进制文件的位置加入PATH搜索路径。
用简单的命令试验成功
export PATH=/par/mold240/bin:$PATH
gcc fib.c -o fibm -fuse-ld=mold
于是修改 /usr/local/cargo/config.toml 为如下
cat /usr/local/cargo/config.toml
[source.crates-io]
replace-with = 'mirror'
[source.mirror]
registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"
[registries.mirror]
index = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"
[target.'cfg(target_os = "linux")']
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
再次执行cargo build成功,全部重新编译用时
Finished `dev` profile [unoptimized + debuginfo] target(s) in 4m 04s
构建速度提高了4倍,得到的二进制文件只比ld生成的略大。