From c652dfa3ecd91b9cbc2424d65a81a4982a84caa1 Mon Sep 17 00:00:00 2001 From: Sage Griffin Date: Wed, 30 Mar 2022 08:28:34 -0600 Subject: [PATCH 1/2] Add support for static linking While tensorflow doesn't officially support building a static library, it is relatively straightforward on Unix using instructions found by the community at https://github.com/tensorflow/tensorflow/issues/28388. This allows tensorflow-sys to use a static library should one already exist. No attempt is made to add any support for automatically building a static library. It is entirely on the user to go through the trouble of producing `libtensorflow.a` should they want to use it. This commit *only* allows the user to ask the build script to use the static library they have built. --- tensorflow-sys/README.md | 3 +++ tensorflow-sys/build.rs | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/tensorflow-sys/README.md b/tensorflow-sys/README.md index 6872695e96..84da1fa7fb 100644 --- a/tensorflow-sys/README.md +++ b/tensorflow-sys/README.md @@ -60,6 +60,9 @@ compiled library will be picked up. **macOS Note**: Via [Homebrew](https://brew.sh/), you can just run `brew install libtensorflow`. +To statically link Tensorflow, set the environment variable +`TENSORFLOW_LIB_STATIC` to the directory containing `libtensorflow.a` + ## Resources [bazel]: http://www.bazel.io diff --git a/tensorflow-sys/build.rs b/tensorflow-sys/build.rs index 7b74be5be0..c2f7629627 100644 --- a/tensorflow-sys/build.rs +++ b/tensorflow-sys/build.rs @@ -44,6 +44,11 @@ fn main() { return; } + if check_static_link() { + log!("Returing early because {} is being statically linked", LIBRARY); + return; + } + if check_windows_lib() { log!("Returning early because {} was already found", LIBRARY); return; @@ -469,3 +474,20 @@ fn check_bazel() -> Result<(), Box> { } Ok(()) } + +fn check_static_link() -> bool { + if let Ok(path) = env::var("TENSORFLOW_LIB_STATIC") { + println!("cargo:rustc-link-search=native={}", path); + println!("cargo:rustc-link-lib=static={}", LIBRARY); + #[cfg(target_os = "linux")] + println!("cargo:rustc-link-lib=dylib=stdc++"); + #[cfg(target_os = "macos")] + { + println!("cargo:rustc-link-lib=c++"); + println!("cargo:rustc-link-lib=framework=foundation"); + } + true + } else { + false + } +} From d3bc6d25ebaf2aaa71dca118e76108abdadbd7ec Mon Sep 17 00:00:00 2001 From: Sage Griffin Date: Tue, 19 Apr 2022 08:24:20 -0600 Subject: [PATCH 2/2] cargo fmt --- tensorflow-sys/build.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tensorflow-sys/build.rs b/tensorflow-sys/build.rs index c2f7629627..0d623d8443 100644 --- a/tensorflow-sys/build.rs +++ b/tensorflow-sys/build.rs @@ -45,7 +45,10 @@ fn main() { } if check_static_link() { - log!("Returing early because {} is being statically linked", LIBRARY); + log!( + "Returing early because {} is being statically linked", + LIBRARY + ); return; }