README.md
1# Hello World with compiler optimization
2
3Each binary target can have its own compiler options, and these can be customised differently for different optimisation levels.
4This takes three steps:
5
61) In your root folder BUILD.bazel, add the following entry:
7
8```Starlark
9config_setting(
10 name = "release",
11 values = {
12 "compilation_mode": "opt",
13 },
14)
15```
16
172) In your binary target, add the optimization flags & strip settings prefixed with -C.
18For a complete list of Rust compiler optimization flag, please read the
19[official cargo documentation](https://doc.rust-lang.org/cargo/reference/profiles.html).
20
21```Starlark
22load("@rules_rust//rust:defs.bzl", "rust_binary")
23
24rust_binary(
25 name = "bin",
26 srcs = ["src/main.rs"],
27 deps = [],
28 rustc_flags = select({
29 "//:release": [
30 "-Clto=true",
31 "-Ccodegen-units=1",
32 "-Cpanic=abort",
33 "-Copt-level=3",
34 "-Cstrip=symbols",
35 ],
36 "//conditions:default":
37 [
38 "-Copt-level=0",
39 ],
40 }),
41 visibility = ["//visibility:public"],
42)
43```
44
45Build with optimization:
46
47`bazel build -c opt //...`
48
49And run the optimized binary:
50
51`bazel run -c opt //...`
52