Skip to content

cfg may not work in build script #37

@zu1k

Description

@zu1k

I'm cross compiling from linux to windows, but I found it not work.

I checked the history issue and found that the problem is still unresolved.

However, in the course of my continuous testing, I found that the cfg conditional judgment in the build script does not work.

My Test Demo

// build.rs

#[cfg(target_os="windows")]
fn main() {
    panic!("target_os = windows")
}

#[cfg(windows)]
fn main() {
    panic!("windows")
}

#[cfg(unix)]
fn main() {
    panic!("unix")
}

host system

$ uname -a
Linux alex 5.13.19-2-MANJARO #1 SMP PREEMPT Sun Sep 19 21:31:53 UTC 2021 x86_64 GNU/Linux

target: x86_64-unknown-linux-gnu (local)

$ cargo build 
   Compiling target v0.1.0 (/data/projects/target)
error: failed to run custom build command for `target v0.1.0 (/data/projects/target)`

Caused by:
  process didn't exit successfully: `/data/projects/target/target/debug/build/target-fff5ba352ad7afdb/build-script-build` (exit status: 101)
  --- stderr
  thread 'main' panicked at 'unix', build.rs:13:5
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

That's fine, however when cross compile...

target: x86_64-pc-windows-gnu (cross compile)

$ cargo build --target x86_64-pc-windows-gnu 
   Compiling target v0.1.0 (/data/projects/target)
error: failed to run custom build command for `target v0.1.0 (/data/projects/target)`

Caused by:
  process didn't exit successfully: `/data/projects/target/target/debug/build/target-fff5ba352ad7afdb/build-script-build` (exit status: 101)
  --- stderr
  thread 'main' panicked at 'unix', build.rs:13:5
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

I expect it to output window or target_os = windows, but it panic at unix

My solution

I think it may be because some features were not determined when build.rs was compiled and the features not been passed to rustc.

I have found some environment variables from the documentation and they can be used to determine target and host.

use std::env;

fn main() {
    if env::var("PROFILE").unwrap() == "release" {
        if let Ok(_) = env::var("CARGO_CFG_WINDOWS") {
            let mut res = winres::WindowsResource::new();
            if let Ok(host) = env::var("HOST") {
                if host.contains("linux") {
                    res.set_toolkit_path("/usr/bin")
                        .set_windres_path("x86_64-w64-mingw32-windres");
                }
            }
            res.set_icon("res/copy-translator.ico").set_language(0x04);
            res.compile().unwrap();
        }
    }
}

Icons are still not set successfully when cross compile fron linux to windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions