Skip to content

Commit 6789e98

Browse files
committed
add build.rs script to set linker flags
1 parent 87b0fdd commit 6789e98

File tree

2 files changed

+43
-4
lines changed

2 files changed

+43
-4
lines changed

.cargo/config.toml

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,5 @@
22
runner = "probe-run --chip stm32g031j6mx"
33
# runner = 'arm-none-eabi-size -G'
44

5-
rustflags = [
6-
"-C", "link-arg=-Tlink.x",
7-
]
8-
95
[build]
106
target = "thumbv6m-none-eabi"

build.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//! This build script copies the `memory.x` file from the crate root into
2+
//! a directory where the linker can always find it at build time.
3+
//! For many projects this is optional, as the linker always searches the
4+
//! project root directory -- wherever `Cargo.toml` is. However, if you
5+
//! are using a workspace or have a more complicated build setup, this
6+
//! build script becomes required. Additionally, by requesting that
7+
//! Cargo re-run the build script whenever `memory.x` is changed,
8+
//! updating `memory.x` ensures a rebuild of the application with the
9+
//! new memory settings.
10+
//!
11+
//! The build script also sets the linker flags to tell it which link script to use.
12+
13+
use std::env;
14+
use std::fs::File;
15+
use std::io::Write;
16+
use std::path::PathBuf;
17+
18+
fn main() {
19+
// Put `memory.x` in our output directory and ensure it's
20+
// on the linker search path.
21+
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
22+
File::create(out.join("memory.x"))
23+
.unwrap()
24+
.write_all(include_bytes!("memory.x"))
25+
.unwrap();
26+
println!("cargo:rustc-link-search={}", out.display());
27+
28+
// By default, Cargo will re-run a build script whenever
29+
// any file in the project changes. By specifying `memory.x`
30+
// here, we ensure the build script is only re-run when
31+
// `memory.x` is changed.
32+
println!("cargo:rerun-if-changed=memory.x");
33+
34+
// Specify linker arguments.
35+
36+
// `--nmagic` is required if memory section addresses are not aligned to 0x10000,
37+
// for example the FLASH and RAM sections in your `memory.x`.
38+
// See https://github.com/rust-embedded/cortex-m-quickstart/pull/95
39+
println!("cargo:rustc-link-arg=--nmagic");
40+
41+
// Set the linker script to the one provided by cortex-m-rt.
42+
println!("cargo:rustc-link-arg=-Tlink.x");
43+
}

0 commit comments

Comments
 (0)