├── .gitignore ├── .travis.yml ├── CHANGES.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bors.toml ├── src ├── gnu.rs ├── lib.rs └── msvc.rs └── windres-test ├── Cargo.toml ├── build.rs ├── src └── main.rs ├── windres-test.ico └── windres-test.rc /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | branches: 3 | only: 4 | - staging 5 | - trying 6 | - master 7 | os: 8 | - windows 9 | language: rust 10 | rust: 11 | - stable-x86_64-pc-windows-msvc 12 | - stable-x86_64-pc-windows-gnu 13 | - beta-x86_64-pc-windows-msvc 14 | - beta-x86_64-pc-windows-gnu 15 | - nightly-x86_64-pc-windows-msvc 16 | - nightly-x86_64-pc-windows-gnu 17 | matrix: 18 | allow_failures: 19 | - rust: beta-x86_64-pc-windows-msvc 20 | - rust: beta-x86_64-pc-windows-gnu 21 | - rust: nightly-x86_64-pc-windows-msvc 22 | - rust: nightly-x86_64-pc-windows-gnu 23 | fast_finish: true 24 | install: 25 | - rustup component add clippy rustfmt 26 | script: 27 | - cargo clippy 28 | - cargo build -p windres-test 29 | - cargo doc --no-deps 30 | - cargo fmt --all -- --check 31 | -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | # windres-rs Changelog 2 | 3 | ## 0.2.2 (27/02/2021) 4 | 5 | * Previous versions of this crate were broken for MSVC targets by a breaking change in Rust (see 6 | https://github.com/rust-lang/rust/pull/72785). This version adds a workaround for the breakage. 7 | * To prevent future breakage, trivial changes were made to parts of the code. This is a refactor, 8 | i.e. no change in behaviour from the previous version, but the minimum working Rust version may 9 | have increased as a result. 10 | 11 | ## 0.2.1 (18/08/2018) 12 | 13 | * Update find-winsdk to 0.2. This fixes Windows 8.1A SDK support and adds support for earlier 14 | versions of the Windows SDK through to v6.0. 15 | 16 | ## 0.2.0 (1/08/2018) 17 | 18 | * The strategy for detecting rc.exe on MSVC ABI targets has changed. Now windres tries the 19 | following, in order: 20 | 21 | 1. The `WindowsSdkVerBinPath` environment variable 22 | 2. The `WindowsSdkDir` environment variable 23 | 3. The Windows 10 SDK bin path for the target arch, via registry query 24 | 4. The Windows 8.1 SDK bin path for the target arch, via registry query 25 | 26 | * The optional dependency on clippy has been removed. Use `cargo clippy` instead. 27 | 28 | ## 0.1.0 (20/10/2017) 29 | 30 | * Initial release. 31 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["windres-test"] 3 | 4 | [package] 5 | name = "windres" 6 | version = "0.2.2" 7 | authors = ["FaultyRAM "] 8 | description = "Compiles Windows resource files (.rc) into a Rust program." 9 | repository = "https://github.com/FaultyRAM/windres-rs" 10 | readme = "README.md" 11 | keywords = ["Windows", "resource", "rc"] 12 | categories = ["development-tools::build-utils"] 13 | license = "Apache-2.0 OR MIT" 14 | 15 | [target.'cfg(target_os = "windows")'.dependencies.concat-string] 16 | version = "1" 17 | 18 | [target.'cfg(all(target_os = "windows", target_env = "msvc"))'.dependencies.find-winsdk] 19 | version = "0.2" 20 | 21 | [package.metadata.docs.rs] 22 | default-target = "x86_64-pc-windows-msvc" 23 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017-2021 FaultyRAM 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included 12 | in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 17 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 18 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 19 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 20 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # windres-rs 2 | 3 | [![Travis CI](https://travis-ci.org/FaultyRAM/windres-rs.svg)][1] 4 | [![Crates.io](https://img.shields.io/crates/v/windres.svg)][2] 5 | [![Docs.rs](https://docs.rs/windres/badge.svg)][3] 6 | 7 | `windres` is a [Rust][4] library crate for compiling [Windows resource (.rc) files][5] into object 8 | files at build time, which are then forwarded to the linker. This allows for embedding icons, 9 | version information, native UI data, etc. in binaries compiled from Rust code. 10 | 11 | ## Example 12 | 13 | The following example demonstrates how to embed an icon in a binary crate: 14 | 15 | ```rc 16 | // hello-world.rc 17 | 18 | 1 ICON "hello-world.ico" 19 | ``` 20 | 21 | ```rust 22 | // build.rs 23 | 24 | extern crate windres; 25 | 26 | use windres::Build; 27 | 28 | fn main() { 29 | Build::new().compile("hello-world.rc").unwrap(); 30 | } 31 | ``` 32 | 33 | ## Usage 34 | 35 | You need to install the resource compiler for your target ABI in order for `windres` to work. 36 | Currently the following compilers are supported: 37 | 38 | * `windres.exe` for GNU targets (included in the [mingw-w64][6] toolchain) 39 | * `rc.exe` for MSVC targets (included in the Windows SDK, which can be installed via Visual Studio 40 | Installer) 41 | 42 | Once the appropriate resource compiler is installed, add `windres` as a build dependency in 43 | `Cargo.toml`: 44 | 45 | ```toml 46 | [target.'cfg(windows)'.build-dependencies] 47 | windres = "0.2" 48 | ``` 49 | 50 | Then, create a build script (if you haven't already) and add a reference to `windres`: 51 | 52 | ```rust 53 | #[cfg(windows)] 54 | extern crate windres; 55 | ``` 56 | 57 | ## License 58 | 59 | Licensed under either of 60 | 61 | * Apache License, Version 2.0, 62 | ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 63 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 64 | 65 | at your option. 66 | 67 | ### Contribution 68 | 69 | Unless you explicitly state otherwise, any contribution intentionally 70 | submitted for inclusion in the work by you, as defined in the Apache-2.0 71 | license, shall be dual licensed as above, without any additional terms or 72 | conditions. 73 | 74 | [1]: https://travis-ci.org/FaultyRAM/windres-rs 75 | [2]: https://crates.io/crates/windres 76 | [3]: https://docs.rs/windres 77 | [4]: https://www.rust-lang.org 78 | [5]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa380599(v=vs.85).aspx 79 | [6]: https://mingw-w64.org 80 | -------------------------------------------------------------------------------- /bors.toml: -------------------------------------------------------------------------------- 1 | status = [ 2 | "continuous-integration/travis-ci/push" 3 | ] 4 | -------------------------------------------------------------------------------- /src/gnu.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017-2021 FaultyRAM 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license , at your option. This file may not be copied, modified, or 6 | // distributed except according to those terms. 7 | 8 | use super::Build; 9 | use std::env; 10 | use std::ffi::{OsStr, OsString}; 11 | use std::io::{self, Write}; 12 | use std::path::{Path, PathBuf}; 13 | use std::process::Command; 14 | 15 | impl Build { 16 | /// Locates the tool used to compile resources. 17 | pub(crate) fn find_resource_compiler() -> io::Result { 18 | env::var_os("PATH") 19 | .and_then(|path| { 20 | env::split_paths(&path) 21 | .map(|p| p.join("windres.exe")) 22 | .find(|p| p.exists()) 23 | }) 24 | .map_or_else( 25 | || { 26 | Err(io::Error::new( 27 | io::ErrorKind::NotFound, 28 | "could not locate windres.exe", 29 | )) 30 | }, 31 | Ok, 32 | ) 33 | } 34 | 35 | /// Invokes the resource compiler using the current arguments. 36 | pub(crate) fn compile_resource>( 37 | &self, 38 | rc_file: P, 39 | compiler: PathBuf, 40 | ) -> io::Result<()> { 41 | let mut cmd = Command::new(compiler); 42 | // User-specific options. 43 | for inc_path in &self.extra_include_dirs { 44 | let _ = cmd.arg(concat_string!("-I", inc_path.to_string_lossy())); 45 | } 46 | for def in &self.extra_cpp_defs { 47 | let s = if let Some(ref v) = def.1 { 48 | concat_string!("-D", def.0, "=", v) 49 | } else { 50 | concat_string!("-D", def.0) 51 | }; 52 | let _ = cmd.arg(s); 53 | } 54 | for undef in &self.cpp_undefs { 55 | let _ = cmd.arg(concat_string!("-U", undef)); 56 | } 57 | // Common options. 58 | let rc_filename = rc_file 59 | .as_ref() 60 | .file_name() 61 | .expect("invalid input filename"); 62 | let mut libname = OsString::from("lib"); 63 | libname.push(&rc_filename); 64 | let out_file = Path::new(&env::var_os("OUT_DIR").expect("`OUT_DIR` is invalid or not set")) 65 | .join(libname) 66 | .with_extension("res.a"); 67 | let _ = cmd.args(&[ 68 | OsStr::new("-Ocoff"), 69 | OsStr::new("-v"), 70 | OsStr::new("-c65001"), 71 | rc_file.as_ref().as_ref(), 72 | out_file.as_ref(), 73 | ]); 74 | cmd.status().and_then(|status| { 75 | if status.success() { 76 | let mut res_filename = Path::new(rc_filename).to_owned(); 77 | let _ = res_filename.set_extension("res"); 78 | let stdout = io::stdout(); 79 | let mut stdout_lock = stdout.lock(); 80 | return stdout_lock.write_all( 81 | concat_string!( 82 | "cargo:rustc-link-search=native=", 83 | out_file.parent().expect("empty parent").to_string_lossy(), 84 | "\n", 85 | "cargo:rustc-link-lib=static=", 86 | res_filename.to_string_lossy(), 87 | "\n", 88 | "cargo:rerun-if-changed=", 89 | rc_file.as_ref().to_string_lossy(), 90 | "\n" 91 | ) 92 | .as_bytes(), 93 | ); 94 | } 95 | let e = if let Some(code) = status.code() { 96 | io::Error::new( 97 | io::ErrorKind::Other, 98 | concat_string!("windres.exe returned exit code ", code.to_string()), 99 | ) 100 | } else { 101 | io::Error::new( 102 | io::ErrorKind::Interrupted, 103 | "child process terminated by signal", 104 | ) 105 | }; 106 | Err(e) 107 | }) 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017-2021 FaultyRAM 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license , at your option. This file may not be copied, modified, or 6 | // distributed except according to those terms. 7 | 8 | //! Compiles Windows resource files (.rc) into a Rust program. 9 | //! 10 | //! This crate provides utilities for compiling .rc files into object files when targeting Windows. 11 | //! .rc files specify icons, version information, and *localisable resources* such as menu strings, 12 | //! which are embedded into a binary at link time. Currently, Rust does not natively support .rc 13 | //! files, so this crate must be used instead to achieve the same effect. 14 | 15 | #![cfg(target_os = "windows")] 16 | #![deny( 17 | clippy::all, 18 | clippy::pedantic, 19 | warnings, 20 | future_incompatible, 21 | rust_2018_idioms, 22 | rustdoc, 23 | unused, 24 | deprecated_in_future, 25 | missing_copy_implementations, 26 | missing_debug_implementations, 27 | non_ascii_idents, 28 | trivial_casts, 29 | trivial_numeric_casts, 30 | unreachable_pub, 31 | unused_import_braces, 32 | unused_lifetimes, 33 | unused_results 34 | )] 35 | #![allow(clippy::must_use_candidate, missing_doc_code_examples)] 36 | 37 | #[macro_use(concat_string)] 38 | extern crate concat_string; 39 | #[cfg(target_env = "msvc")] 40 | extern crate find_winsdk; 41 | 42 | use std::io; 43 | use std::path::{Path, PathBuf}; 44 | 45 | #[cfg(target_env = "gnu")] 46 | #[path = "gnu.rs"] 47 | mod imp; 48 | #[cfg(target_env = "msvc")] 49 | #[path = "msvc.rs"] 50 | mod imp; 51 | 52 | #[derive(Clone, Debug)] 53 | /// A builder for compiling Windows resources. 54 | pub struct Build { 55 | /// A list of additional include paths to use during preprocessing. 56 | extra_include_dirs: Vec, 57 | /// A list of additional preprocessor definitions to use during preprocessing. 58 | extra_cpp_defs: Vec<(String, Option)>, 59 | /// A list of preprocessor symbols to undefine during preprocessing. 60 | cpp_undefs: Vec, 61 | } 62 | 63 | impl Build { 64 | /// Creates a new, empty builder. 65 | pub fn new() -> Self { 66 | Self { 67 | extra_include_dirs: Vec::new(), 68 | extra_cpp_defs: Vec::new(), 69 | cpp_undefs: Vec::new(), 70 | } 71 | } 72 | 73 | /// Specifies an additional include path to use during preprocessing. 74 | pub fn include>(&mut self, path: P) -> &mut Self { 75 | self.extra_include_dirs.push(path.as_ref().to_owned()); 76 | self 77 | } 78 | 79 | /// Specifies an additional preprocessor definition to use during preprocessing. 80 | pub fn define<'a, V: Into>>(&mut self, name: &str, value: V) -> &mut Self { 81 | self.extra_cpp_defs 82 | .push((name.to_owned(), value.into().map(ToOwned::to_owned))); 83 | self 84 | } 85 | 86 | /// Specifies a preprocessor symbol to undefine during preprocessing. 87 | pub fn undefine(&mut self, name: &str) -> &mut Self { 88 | self.cpp_undefs.push(name.to_owned()); 89 | self 90 | } 91 | 92 | /// Compiles a Windows resource file (.rc). 93 | /// 94 | /// # Errors 95 | /// 96 | /// This method returns a `std::io::Error` if it either cannot locate a resource compiler or 97 | /// fails to compile the resource. 98 | pub fn compile>(&mut self, rc_file: P) -> io::Result<()> { 99 | Self::find_resource_compiler().and_then(|compiler| self.compile_resource(rc_file, compiler)) 100 | } 101 | } 102 | 103 | impl Default for Build { 104 | fn default() -> Self { 105 | Self::new() 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/msvc.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017-2021 FaultyRAM 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license , at your option. This file may not be copied, modified, or 6 | // distributed except according to those terms. 7 | 8 | //! MSVC implementation details. 9 | 10 | use super::Build; 11 | use find_winsdk::{SdkInfo, SdkVersion}; 12 | use std::env; 13 | use std::ffi::{OsStr, OsString}; 14 | use std::io::{self, ErrorKind, Write}; 15 | use std::path::{Path, PathBuf}; 16 | use std::process::Command; 17 | 18 | #[cfg(target_arch = "x86")] 19 | const RC_EXE: &str = "x86/rc.exe"; 20 | #[cfg(target_arch = "x86_64")] 21 | const RC_EXE: &str = "x64/rc.exe"; 22 | #[cfg(target_arch = "arm")] 23 | const RC_EXE: &str = "arm/rc.exe"; 24 | #[cfg(target_arch = "aarch64")] 25 | const RC_EXE: &str = "arm64/rc.exe"; 26 | 27 | impl Build { 28 | /// Locates the tool used to compile resources. 29 | pub(crate) fn find_resource_compiler() -> io::Result { 30 | if let Some(bin_path) = env::var_os("WindowsSdkVerBinPath") { 31 | Ok(Path::new(&bin_path).join(RC_EXE)) 32 | } else { 33 | match SdkInfo::find(SdkVersion::Any) { 34 | Ok(Some(info)) => { 35 | let path_suffix = if info.product_version().starts_with("10.") { 36 | concat_string!("bin/", info.product_version(), ".0/", RC_EXE) 37 | } else { 38 | concat_string!("bin/", RC_EXE) 39 | }; 40 | Ok(Path::new(info.installation_folder()).join(path_suffix)) 41 | } 42 | Ok(None) => Err(io::Error::new( 43 | ErrorKind::NotFound, 44 | "could not locate a Windows SDK installation", 45 | )), 46 | Err(e) => Err(e), 47 | } 48 | } 49 | } 50 | 51 | /// Invokes the resource compiler using the current arguments. 52 | pub(crate) fn compile_resource>( 53 | &self, 54 | rc_file: P, 55 | compiler: PathBuf, 56 | ) -> io::Result<()> { 57 | let mut cmd = Command::new(compiler); 58 | // User-specific options. 59 | for inc_path in &self.extra_include_dirs { 60 | let _ = cmd.arg(concat_string!("/i", inc_path.to_string_lossy())); 61 | } 62 | for def in &self.extra_cpp_defs { 63 | let s = if let Some(ref v) = def.1 { 64 | concat_string!("/d", def.0, "=", v) 65 | } else { 66 | concat_string!("/d", def.0) 67 | }; 68 | let _ = cmd.arg(s); 69 | } 70 | for undef in &self.cpp_undefs { 71 | let _ = cmd.arg(concat_string!("/u", undef)); 72 | } 73 | // Common options. 74 | let rc_filename = rc_file 75 | .as_ref() 76 | .file_name() 77 | .expect("invalid input filename"); 78 | let out_file = Path::new(&env::var_os("OUT_DIR").expect("`OUT_DIR` is invalid or not set")) 79 | .join(rc_filename) 80 | .with_extension("res.lib"); 81 | let mut fo = OsString::from("/fo"); 82 | fo.push(&out_file); 83 | let _ = cmd.args(&[ 84 | &fo, 85 | OsStr::new("/v"), 86 | OsStr::new("/nologo"), 87 | OsStr::new("/c65001"), 88 | rc_file.as_ref().as_ref(), 89 | ]); 90 | cmd.status().and_then(|status| { 91 | if status.success() { 92 | let stdout = io::stdout(); 93 | let mut stdout_lock = stdout.lock(); 94 | return stdout_lock.write_all( 95 | concat_string!( 96 | "cargo:rustc-link-search=native=", 97 | out_file.parent().expect("empty parent").to_string_lossy(), 98 | "\n", 99 | "cargo:rustc-link-lib=", 100 | out_file 101 | .file_stem() 102 | .expect("empty filename") 103 | .to_string_lossy(), 104 | "\n", 105 | "cargo:rerun-if-changed=", 106 | rc_file.as_ref().to_string_lossy(), 107 | "\n" 108 | ) 109 | .as_bytes(), 110 | ); 111 | } 112 | let e = if let Some(code) = status.code() { 113 | io::Error::new( 114 | io::ErrorKind::Other, 115 | concat_string!("rc.exe returned exit code ", code.to_string()), 116 | ) 117 | } else { 118 | io::Error::new( 119 | io::ErrorKind::Interrupted, 120 | "child process terminated by signal", 121 | ) 122 | }; 123 | Err(e) 124 | }) 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /windres-test/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "windres-test" 3 | version = "0.1.0" 4 | authors = ["FaultyRAM "] 5 | workspace = ".." 6 | publish = false 7 | 8 | [target.'cfg(windows)'.build-dependencies.windres] 9 | path = ".." 10 | -------------------------------------------------------------------------------- /windres-test/build.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017-2021 FaultyRAM 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license , at your option. This file may not be copied, modified, or 6 | // distributed except according to those terms. 7 | 8 | #[cfg(windows)] 9 | extern crate windres; 10 | 11 | #[cfg(windows)] 12 | use windres::Build; 13 | 14 | #[cfg(windows)] 15 | fn main() { 16 | Build::new().compile("windres-test.rc").unwrap(); 17 | } 18 | 19 | #[cfg(not(windows))] 20 | fn main() {} 21 | -------------------------------------------------------------------------------- /windres-test/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017-2021 FaultyRAM 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license , at your option. This file may not be copied, modified, or 6 | // distributed except according to those terms. 7 | 8 | fn main() {} 9 | -------------------------------------------------------------------------------- /windres-test/windres-test.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FaultyRAM/windres-rs/9ac7f25dfdc40f6a0ee24e52116a73746620feb5/windres-test/windres-test.ico -------------------------------------------------------------------------------- /windres-test/windres-test.rc: -------------------------------------------------------------------------------- 1 | 1 ICON "windres-test.ico" 2 | --------------------------------------------------------------------------------