rustrust-cargo

How to specify -fPIC and -fPIE options when building Rust binaries


In GCC we can specify -fPIC option for shared library and -fPIE for executable to create code that can be executed at any memory address. How do I achieve the same in Rust using Cargo?


Solution

    1. Create a new Cargo package
      cargo new --lib <name>
      
      This command will create a package with a library target and the file src/lib.rs.
    2. Open Cargo.toml and add or modify crate-type in the [lib] section.
      [lib]
      crate-type = ["cdylib"]
      
      This will guide a linker to output a position independent code for a shared library.

    Rust, by default, builds PIE executables on most modern platforms that support them.