├── common ├── CMakeLists.txt └── gen_uuid │ ├── Cargo.toml │ ├── CMakeLists.txt │ ├── src │ └── lib.rs │ ├── cbindgen.toml │ └── build.rs ├── Cargo.toml ├── lib ├── c │ ├── dostuff.h │ ├── demo.h │ ├── demo-private.h │ ├── dostuff.c │ ├── demo.c │ ├── demo-version.h.in │ └── CMakeLists.txt ├── rust │ ├── src │ │ ├── lib.rs │ │ ├── sys.rs │ │ ├── do_thing.rs │ │ └── colorlog.rs │ ├── Cargo.toml │ ├── CMakeLists.txt │ ├── cbindgen.toml │ └── build.rs └── CMakeLists.txt ├── app_rust ├── src │ └── main.rs ├── Cargo.toml ├── CMakeLists.txt └── build.rs ├── test └── CMakeLists.txt ├── app_c ├── CMakeLists.txt └── app.c ├── run-clang-format.sh ├── LICENSE-MIT.md ├── .gitignore ├── CMakeLists.txt ├── .github └── workflows │ └── main.yml ├── .clang-format ├── README.md ├── LICENSE-Apache-2.0.md └── cmake └── FindRust.cmake /common/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2022 Micah Snyder. 2 | 3 | add_subdirectory(gen_uuid) 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = ["lib/rust", "common/gen_uuid", "app_rust"] 4 | 5 | [profile.dev.package."*"] 6 | opt-level = 2 7 | -------------------------------------------------------------------------------- /lib/c/dostuff.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | bool do_the_thing(uint8_t *inout, size_t inout_size); 6 | -------------------------------------------------------------------------------- /app_rust/src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Example rust app. 3 | * 4 | * Copyright (C) 2022 Micah Snyder. 5 | */ 6 | 7 | fn main() { 8 | let uuid = gen_uuid::gen_uuid(); 9 | println!("Hello, {}!", uuid); 10 | } 11 | -------------------------------------------------------------------------------- /lib/rust/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * demo features ported to Rust 3 | * 4 | * Copyright (C) 2020-2022 Micah Snyder. 5 | */ 6 | 7 | /// cbindgen:ignore 8 | pub mod sys; 9 | 10 | pub mod colorlog; 11 | pub mod do_thing; 12 | -------------------------------------------------------------------------------- /app_rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Micah Snyder"] 3 | edition = "2021" 4 | name = "app_rust" 5 | version = "0.1.0" 6 | 7 | [dependencies] 8 | gen_uuid = { path = "../common/gen_uuid" } 9 | 10 | [build-dependencies] 11 | bindgen = "0.59" 12 | -------------------------------------------------------------------------------- /lib/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2022 Micah Snyder. 2 | 3 | # 4 | # The demo Rust library (features ported from the "original" C library to Rust) 5 | # 6 | add_subdirectory(rust) 7 | 8 | # The demo C library 9 | # 10 | add_subdirectory(c) 11 | -------------------------------------------------------------------------------- /lib/c/demo.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020-2022 Micah Snyder. 3 | */ 4 | 5 | #ifndef __DEMO_H 6 | #define __DEMO_H 7 | 8 | #include "demo-version.h" 9 | 10 | void cmakerust_init(); 11 | 12 | void cmakerust_fini(); 13 | 14 | #endif /* __DEMO_H */ 15 | -------------------------------------------------------------------------------- /lib/c/demo-private.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 Micah Snyder. 3 | */ 4 | 5 | #ifndef __LIB_PRIVATE_H 6 | #define __LIB_PRIVATE_H 7 | 8 | const char* init_message = "Initialized!"; 9 | const char* fini_message = "Finito!"; 10 | 11 | #endif /* __CMAKERUST_H */ 12 | -------------------------------------------------------------------------------- /lib/rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Micah Snyder"] 3 | edition = "2021" 4 | name = "demorust" 5 | version = "0.2.0" 6 | 7 | [dependencies] 8 | colored = "2.0.0" 9 | 10 | [lib] 11 | crate-type = ["staticlib"] 12 | name = "demorust" 13 | 14 | [build-dependencies] 15 | cbindgen = "0.20" 16 | bindgen = "0.59" 17 | -------------------------------------------------------------------------------- /lib/c/dostuff.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | bool do_the_thing(uint8_t *inout, size_t inout_size) 6 | { 7 | // manipulate the input 8 | size_t i; 9 | 10 | for (i = 0; i < inout_size; i++) { 11 | inout[i] *= 2; 12 | } 13 | 14 | return true; 15 | } 16 | -------------------------------------------------------------------------------- /lib/rust/src/sys.rs: -------------------------------------------------------------------------------- 1 | /* automatically generated by rust-bindgen 0.59.2 */ 2 | 3 | #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] 4 | 5 | pub type __uint8_t = ::std::os::raw::c_uchar; 6 | pub type size_t = ::std::os::raw::c_ulong; 7 | extern "C" { 8 | pub fn do_the_thing(inout: *mut u8, inout_size: size_t) -> bool; 9 | } 10 | -------------------------------------------------------------------------------- /common/gen_uuid/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Micah Snyder"] 3 | edition = "2021" 4 | name = "gen_uuid" 5 | version = "0.2.0" 6 | 7 | [dependencies] 8 | libc = "0.2.77" 9 | 10 | [dependencies.uuid] 11 | version = "0.8.1" 12 | features = ["v4"] 13 | 14 | [lib] 15 | crate-type = ["staticlib", "lib"] 16 | name = "gen_uuid" 17 | 18 | [build-dependencies] 19 | cbindgen = "0.20" 20 | -------------------------------------------------------------------------------- /lib/c/demo.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Example library that has some features written in Rust. 3 | * 4 | * Copyright (C) 2020-2022 Micah Snyder. 5 | */ 6 | 7 | #include 8 | #include 9 | 10 | #include "demo-private.h" 11 | #include "demo.h" 12 | #include "demo-rust.h" 13 | 14 | void cmakerust_init() 15 | { 16 | clog_debug((const uint8_t *)init_message, strlen(init_message)); 17 | } 18 | 19 | void cmakerust_fini() 20 | { 21 | clog_debug((const uint8_t *)fini_message, strlen(fini_message)); 22 | } 23 | -------------------------------------------------------------------------------- /test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2022 Micah Snyder. 2 | 3 | # 4 | # Targets for all the application tests and main library unit tests. 5 | # 6 | 7 | if(WIN32) 8 | file(TO_NATIVE_PATH $ LIBDEMO) 9 | else() 10 | set(LIBDEMO $) 11 | endif() 12 | 13 | set(ENVIRONMENT 14 | LIBDEMO=${LIBDEMO} 15 | ) 16 | 17 | add_rust_test(NAME demorust 18 | SOURCE_DIRECTORY "${CMAKE_SOURCE_DIR}/lib/rust" 19 | BINARY_DIRECTORY "${CMAKE_BINARY_DIR}" 20 | ) 21 | set_property(TEST demorust PROPERTY ENVIRONMENT ${ENVIRONMENT}) 22 | -------------------------------------------------------------------------------- /app_rust/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2022 Micah Snyder. 2 | 3 | # 4 | # Rust executable 5 | # 6 | # Example app that links with our C (and Rust) libs. 7 | # 8 | 9 | add_rust_executable(TARGET app_rust 10 | SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 11 | BINARY_DIRECTORY "${CMAKE_BINARY_DIR}" 12 | ) 13 | # Linking with C libraries is done within `build.rs` 14 | # Linking with nearby Rust crates is done within `Cargo.toml` 15 | get_target_property(app_rust_EXECUTABLE app_rust IMPORTED_LOCATION) 16 | install(PROGRAMS ${app_rust_EXECUTABLE} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT programs) 17 | -------------------------------------------------------------------------------- /app_c/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2022 Micah Snyder. 2 | 3 | # 4 | # C executable 5 | # 6 | # Example app that used a static lib written in Rust and a traditional 7 | # shared library written in C with some Rust sprinkled in. 8 | # 9 | 10 | add_executable(app_c) 11 | target_sources(app_c PRIVATE app.c) 12 | target_link_libraries(app_c 13 | PRIVATE 14 | demo::rust_static_lib 15 | demo::static_lib 16 | demo::gen_uuid) 17 | if(WIN32) 18 | target_link_libraries(app_c 19 | PRIVATE 20 | Bcrypt) 21 | endif() 22 | install(TARGETS app_c DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT programs) 23 | -------------------------------------------------------------------------------- /run-clang-format.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | clang-format -style='{ Language: Cpp, UseTab: Never, IndentWidth: 4, AlignTrailingComments: true, AlignConsecutiveAssignments: true, AlignAfterOpenBracket: true, AlignEscapedNewlines: Left, AlignOperands: true, AllowShortFunctionsOnASingleLine: Empty, AllowShortIfStatementsOnASingleLine: true, AllowShortLoopsOnASingleLine: true, BreakBeforeBraces: Linux, BreakBeforeTernaryOperators: true, ColumnLimit: 0, FixNamespaceComments: true, SortIncludes: false, MaxEmptyLinesToKeep: 1, SpaceBeforeParens: ControlStatements, IndentCaseLabels: true, DerivePointerAlignment: true }' -dump-config > .clang-format 4 | 5 | find ./ -iname *.h -o -iname *.c | xargs clang-format -i -verbose 6 | -------------------------------------------------------------------------------- /lib/c/demo-version.h.in: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 Micah Snyder. 3 | * 4 | * @GENERATE_WARNING@ 5 | */ 6 | 7 | #ifndef __CMAKERUST_VER_H 8 | #define __CMAKERUST_VER_H 9 | 10 | /** 11 | * @macro 12 | * Version number of the cmakerust library. 13 | */ 14 | #define LIBCMAKERUST_VERSION "@LIB_VERSION@" 15 | 16 | /** 17 | * @macro 18 | * Numerical representation of the version number of the cmakerust library. 19 | * 20 | * This is a 24 bit number with: 21 | * - 8 bits for major number 22 | * - 8 bits for minor number 23 | * - 8 bits for patch number. 24 | * 25 | * Eg: Version 1.2.3 becomes 0x010203. 26 | */ 27 | #define LIBCMAKERUST_VERSION_NUM @LIB_VERSION_NUM@ 28 | 29 | #endif /* __CMAKERUST_VER_H */ 30 | -------------------------------------------------------------------------------- /common/gen_uuid/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2022 Micah Snyder. 2 | 3 | # 4 | # Libraries that may be used by the applications. 5 | # 6 | 7 | # A library to generate UUID's 8 | add_rust_library(TARGET gen_uuid 9 | SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 10 | BINARY_DIRECTORY "${CMAKE_BINARY_DIR}" 11 | ) 12 | 13 | # The unit tests for this module have no dependencies on C libraries or other special 14 | # test environment considerations, so we may as well add the test right here instead of 15 | # adding it in the `test/CMakeLists.txt` file. 16 | add_rust_test(NAME gen_uuid 17 | SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 18 | BINARY_DIRECTORY "${CMAKE_BINARY_DIR}" 19 | ) 20 | add_library(demo::gen_uuid ALIAS gen_uuid) 21 | -------------------------------------------------------------------------------- /app_c/app.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Sample application that uses a common lib to generate a UUID 3 | * and uses the CMakeRust library's colorlog featuer toe log the UUID. 4 | * 5 | * Copyright 2020 (C) Micah Snyder 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | #include "demo-rust.h" 12 | #include "gen_uuid.h" 13 | 14 | int main(void) 15 | { 16 | char *my_uuid = {0}; 17 | 18 | my_uuid = gen_uuid(); 19 | 20 | printf("%s\n", my_uuid); 21 | clog_debug((const uint8_t *)my_uuid, strlen(my_uuid)); 22 | clog_info((const uint8_t *)my_uuid, strlen(my_uuid)); 23 | clog_warning((const uint8_t *)my_uuid, strlen(my_uuid)); 24 | clog_error((const uint8_t *)my_uuid, strlen(my_uuid)); 25 | 26 | free_uuid(my_uuid); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /lib/rust/src/do_thing.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Example module that uses cbindgen generated bindings (sys.rs) 3 | * 4 | * Copyright (C) 2022 Micah Snyder. 5 | */ 6 | 7 | use crate::sys; 8 | 9 | /// A rust function that may be called from C, and also itself calls into C 10 | /// 11 | /// # Safety 12 | /// 13 | /// inout must be a valid pointer to some mutable data of size inout_len 14 | #[no_mangle] 15 | pub unsafe extern "C" fn do_thing_with_call_into_c(inout: *mut u8, inout_len: usize) -> bool { 16 | sys::do_the_thing(inout, inout_len.try_into().unwrap()) 17 | } 18 | 19 | #[cfg(test)] 20 | mod tests { 21 | use super::do_thing_with_call_into_c; 22 | 23 | #[test] 24 | fn test_do_thing_with_call_into_c() { 25 | let x = &mut [1, 2, 3]; 26 | 27 | let ret = unsafe { do_thing_with_call_into_c(x.as_mut_ptr(), x.len()) }; 28 | 29 | assert_eq!(ret, true); 30 | 31 | assert_eq!(x, &[2, 4, 6]); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LICENSE-MIT.md: -------------------------------------------------------------------------------- 1 | Copyright 2020 Micah Snyder 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /common/gen_uuid/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Example static lib for use in project apps 3 | * 4 | * Copyright (C) 2020-2022 Micah Snyder. 5 | */ 6 | 7 | use libc::c_char; 8 | use std::ffi::CString; 9 | 10 | use uuid::Uuid; 11 | 12 | /// Generate / allocate a UUID structure 13 | #[export_name = "gen_uuid"] 14 | pub extern "C" fn _gen_uuid() -> *mut c_char { 15 | let uuid_str = gen_uuid(); 16 | 17 | let c_uuid = CString::new(uuid_str).unwrap(); 18 | c_uuid.into_raw() 19 | } 20 | 21 | /// Rust function that generates a UUID string 22 | pub fn gen_uuid() -> String { 23 | Uuid::new_v4().to_string() 24 | } 25 | 26 | /// Free a UUID structure 27 | /// 28 | /// # Safety 29 | /// 30 | /// uuid_ptr must be a valid pointer. 31 | #[export_name = "free_uuid"] 32 | pub unsafe extern "C" fn _free_uuid(uuid_ptr: *mut c_char) { 33 | if uuid_ptr.is_null() { 34 | return; 35 | } 36 | let _ = CString::from_raw(uuid_ptr); 37 | } 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | /// faux test to demonstrate running rust unit tests through CMake / CTest 42 | #[test] 43 | fn test_gen_uuid() { 44 | assert_eq!(2 + 2, 4); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /lib/rust/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2022 Micah Snyder. 2 | 3 | # 4 | # The demo Rust library (features ported from the "original" C library to Rust) 5 | # 6 | # Note: The rust port will be compiled to static library target and must be added as 7 | # a dependency to both the C object targets and shared/static library targets. 8 | # 9 | add_rust_library(TARGET demorust 10 | SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 11 | BINARY_DIRECTORY "${CMAKE_BINARY_DIR}" 12 | ) 13 | if (WIN32) 14 | # You can add link library dependencies for the rust libarry target, if you need. 15 | target_link_libraries(demorust PUBLIC INTERFACE Userenv) 16 | endif() 17 | 18 | install(FILES $ DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) 19 | add_library(demo::rust_static_lib ALIAS demorust) 20 | 21 | # The unit tests for the demorust module dependends on the C library and may even need 22 | # to be linked with the C library's 3rd party library dependencies. So to be able to build 23 | # that application, we'll need to pass these things through the environment. 24 | # Thus, we'll set all of that up and add the Rust-test in `tests/CMakelists.txt`. 25 | -------------------------------------------------------------------------------- /common/gen_uuid/cbindgen.toml: -------------------------------------------------------------------------------- 1 | # To view thetemplate cbindgen.toml file with all of the default values, visit: 2 | # https://github.com/eqrion/cbindgen/blob/master/template.toml 3 | # 4 | # See https://github.com/eqrion/cbindgen/blob/master/docs.md#cbindgentoml 5 | # for detailed documentation of every option. 6 | 7 | language = "C" 8 | 9 | ############## Options for Wrapping the Contents of the Header ################# 10 | 11 | header = "/* Copyright (C) 2020 Micah Snyder. */" 12 | include_guard = "__GEN_UUID_H" 13 | autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */" 14 | sys_includes = [] 15 | includes = [] 16 | no_includes = false 17 | after_includes = "" 18 | 19 | [export] 20 | include = ["gen_uuid", "free_uuid"] 21 | exclude = [] 22 | # prefix = "CAPI_" 23 | item_types = [] 24 | renaming_overrides_prefixing = false 25 | 26 | ############## Options for How Your Rust library Should Be Parsed ############## 27 | 28 | [parse] 29 | parse_deps = false 30 | # include = [] 31 | exclude = [] 32 | clean = false 33 | extra_bindings = [] 34 | 35 | [parse.expand] 36 | crates = [] 37 | all_features = false 38 | default_features = true 39 | features = [] 40 | -------------------------------------------------------------------------------- /lib/rust/cbindgen.toml: -------------------------------------------------------------------------------- 1 | # To view thetemplate cbindgen.toml file with all of the default values, visit: 2 | # https://github.com/eqrion/cbindgen/blob/master/template.toml 3 | # 4 | # See https://github.com/eqrion/cbindgen/blob/master/docs.md#cbindgentoml 5 | # for detailed documentation of every option. 6 | 7 | language = "C" 8 | 9 | ############## Options for Wrapping the Contents of the Header ################# 10 | 11 | header = "/* Copyright (C) 2020-2022 Micah Snyder. */" 12 | include_guard = "__DEMORUST_H" 13 | autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */" 14 | sys_includes = [] 15 | includes = [] 16 | no_includes = false 17 | after_includes = "" 18 | 19 | [export] 20 | include = ["clog_debug", "clog_info", "clog_warning", "clog_error"] 21 | exclude = [] 22 | # prefix = "CAPI_" 23 | item_types = [] 24 | renaming_overrides_prefixing = false 25 | 26 | ############## Options for How Your Rust library Should Be Parsed ############## 27 | 28 | [parse] 29 | parse_deps = false 30 | # include = [] 31 | exclude = [] 32 | clean = false 33 | extra_bindings = [] 34 | 35 | [parse.expand] 36 | crates = [] 37 | all_features = false 38 | default_features = true 39 | features = [] 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # CMake 2 | CMakeLists.txt.user 3 | CMakeCache.txt 4 | CMakeFiles 5 | CMakeScripts 6 | Testing 7 | Makefile 8 | cmake_install.cmake 9 | install_manifest.txt 10 | compile_commands.json 11 | CTestTestfile.cmake 12 | 13 | # Ninja 14 | .ninja_deps 15 | .ninja_log 16 | 17 | # C Prerequisites 18 | *.d 19 | 20 | # C Object files 21 | *.o 22 | *.ko 23 | *.obj 24 | *.elf 25 | 26 | # C Linker output 27 | *.ilk 28 | *.map 29 | *.exp 30 | 31 | # C Precompiled Headers 32 | *.gch 33 | *.pch 34 | 35 | # C Libraries 36 | *.lib 37 | *.a 38 | *.la 39 | *.lo 40 | 41 | # C Shared objects (inc. Windows DLLs) 42 | *.dll 43 | *.so 44 | *.so.* 45 | *.dylib 46 | 47 | # C Executables 48 | *.exe 49 | *.out 50 | *.app 51 | *.i*86 52 | *.x86_64 53 | *.hex 54 | 55 | # C Debug files 56 | *.dSYM/ 57 | *.su 58 | *.idb 59 | *.pdb 60 | 61 | # Editor save files 62 | *~ 63 | 64 | # Vim Swap 65 | [._]*.s[a-v][a-z] 66 | [._]*.sw[a-p] 67 | [._]s[a-rt-v][a-z] 68 | [._]ss[a-gi-z] 69 | [._]sw[a-p] 70 | 71 | # Vim Session 72 | Session.vim 73 | 74 | # Vim Temporary 75 | .netrwhist 76 | *~ 77 | # Vim Auto-generated tag files 78 | tags 79 | # Vim Persistent undo 80 | [._]*.un~ 81 | 82 | # VScode config 83 | .vscode 84 | 85 | # Build directories 86 | install/* 87 | build/* 88 | 89 | # Rust / Cargo files 90 | Cargo.lock 91 | target/* 92 | -------------------------------------------------------------------------------- /lib/c/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2022 Micah Snyder. 2 | 3 | configure_file(demo-version.h.in demo-version.h) 4 | 5 | # 6 | # The demo C library 7 | # 8 | add_library(demo_obj OBJECT) 9 | target_sources(demo_obj 10 | PRIVATE 11 | demo.c demo-private.h 12 | dostuff.c dostuff.h 13 | PUBLIC 14 | demo.h 15 | ) 16 | target_link_libraries(demo_obj PUBLIC demorust) 17 | if(WIN32) 18 | target_link_libraries(demo_obj PUBLIC Userenv wsock32 ws2_32) 19 | endif() 20 | target_include_directories(demo_obj PUBLIC ${CMAKE_CURRENT_BINARY_DIR}) 21 | 22 | # The demo shared library. 23 | add_library(demo SHARED) 24 | target_sources(demo PUBLIC demo.h) 25 | target_link_libraries(demo PUBLIC demo_obj) 26 | target_include_directories(demo PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) 27 | if(WIN32) 28 | set_target_properties(demo PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON) 29 | target_link_libraries(demo PRIVATE Bcrypt) 30 | endif() 31 | install(TARGETS demo DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) 32 | add_library(demo::lib ALIAS demo) 33 | 34 | # The demo static library. 35 | add_library(demo_static STATIC) 36 | target_sources(demo_static PUBLIC demo.h) 37 | target_link_libraries(demo_static PUBLIC demo_obj) 38 | target_include_directories(demo PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) 39 | set_target_properties(demo_static PROPERTIES ARCHIVE_OUTPUT_NAME demo_static) 40 | install(TARGETS demo_static DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) 41 | add_library(demo::static_lib ALIAS demo_static) 42 | -------------------------------------------------------------------------------- /common/gen_uuid/build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::path::PathBuf; 3 | 4 | const C_HEADER_OUTPUT: &str = "gen_uuid.h"; 5 | 6 | // Environment variable name prefixes worth including for diags 7 | const ENV_PATTERNS: &[&str] = &["CARGO_", "RUST", "LIB"]; 8 | 9 | fn main() -> Result<(), &'static str> { 10 | eprintln!("build.rs command line: {:?}", std::env::args()); 11 | eprintln!("Environment:"); 12 | std::env::vars() 13 | .filter(|(k, _)| ENV_PATTERNS.iter().any(|prefix| k.starts_with(prefix))) 14 | .for_each(|(k, v)| eprintln!(" {}={:?}", k, v)); 15 | 16 | // We only want to generate bindings for `cargo build`, not `cargo test`. 17 | // FindRust.cmake defines $CARGO_CMD so we can differentiate. 18 | let cargo_cmd = env::var("CARGO_CMD").unwrap_or_else(|_| "".into()); 19 | 20 | match cargo_cmd.as_str() { 21 | "build" => { 22 | // Generate bindings as a part of the build. 23 | 24 | // Always generate the C-headers when CMake kicks off a build. 25 | generate_c_bindings()?; 26 | 27 | // No rust bindings needed. This module doesn't call into our C libs. 28 | } 29 | 30 | _ => { 31 | return Ok(()); 32 | } 33 | } 34 | 35 | Ok(()) 36 | } 37 | 38 | /// Use cbindgen to generate C-headers for Rust library. 39 | fn generate_c_bindings() -> Result<(), &'static str> { 40 | let crate_dir = env::var("CARGO_MANIFEST_DIR").or(Err("CARGO_MANIFEST_DIR not specified"))?; 41 | let build_dir = PathBuf::from(env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| ".".into())); 42 | let outfile_path = build_dir.join(C_HEADER_OUTPUT); 43 | 44 | // Useful for build diagnostics 45 | eprintln!("cbindgen outputting {:?}", &outfile_path); 46 | cbindgen::generate(crate_dir) 47 | .expect("Unable to generate C headers for Rust code") 48 | .write_to_file(&outfile_path); 49 | 50 | Ok(()) 51 | } 52 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2022 Micah Snyder. 2 | 3 | cmake_minimum_required(VERSION 3.18) 4 | set(RUSTC_MINIMUM_REQUIRED 1.56) 5 | 6 | project(RustCMakeDemo 7 | VERSION "0.2.0" 8 | DESCRIPTION "A demo app to show a CMake project with components written in Rust.") 9 | 10 | set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) 11 | 12 | # 13 | # Find Build Tools 14 | # 15 | set(MAINTAINER_MODE_DEFAULT OFF) 16 | option(MAINTAINER_MODE 17 | "Use `cbindgen` to generate Rust library API headers." 18 | ${MAINTAINER_MODE_DEFAULT}) 19 | 20 | find_package(Rust REQUIRED) 21 | 22 | # Always use '-fPIC'/'-fPIE' option. 23 | set(CMAKE_POSITION_INDEPENDENT_CODE ON) 24 | 25 | # Include GNUInstallDirs for access to CMAKE_INSTALL_LIBDIR, etc 26 | include(GNUInstallDirs) 27 | 28 | # Enable CTest 29 | if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) 30 | include(CTest) 31 | enable_testing() 32 | endif() 33 | 34 | # Enable source packages with CTest 35 | set(CPACK_SOURCE_GENERATOR "TGZ") 36 | set(CPACK_SOURCE_PACKAGE_FILE_NAME cmake-rust-${PROJECT_VERSION}) 37 | set(CPACK_SOURCE_IGNORE_FILES 38 | \\.git/ 39 | build/ 40 | ".*~$" 41 | ) 42 | set(CPACK_VERBATIM_VARIABLES YES) 43 | include(CPack) 44 | 45 | # 46 | # Build targets. 47 | # 48 | add_subdirectory(lib) 49 | add_subdirectory(common) 50 | add_subdirectory(app_c) 51 | add_subdirectory(app_rust) 52 | add_subdirectory(test) 53 | 54 | # 55 | # The Summary Info. 56 | # 57 | string(TOUPPER "${CMAKE_BUILD_TYPE}" _build_type) 58 | message(STATUS "Configuration Options Summary -- 59 | Target system: ${CMAKE_SYSTEM} 60 | Compiler: 61 | Build type: ${CMAKE_BUILD_TYPE} 62 | C compiler: ${CMAKE_C_COMPILER} 63 | Rust toolchain: ${cargo_EXECUTABLE} (${cargo_VERSION}) 64 | ${rustc_EXECUTABLE} (${rustc_VERSION}) 65 | CFLAGS: ${CMAKE_C_FLAGS_${_build_type}} ${CMAKE_C_FLAGS} 66 | Build Options: 67 | Maintainer Mode: ${MAINTAINER_MODE}") 68 | -------------------------------------------------------------------------------- /lib/rust/src/colorlog.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Example static lib for use in project apps 3 | * 4 | * Copyright (C) 2020 Micah Snyder. 5 | */ 6 | 7 | use colored::*; 8 | 9 | enum LogLevel { 10 | Debug, 11 | Info, 12 | Warning, 13 | Error, 14 | } 15 | 16 | fn clog(level: LogLevel, message: &str) { 17 | match level { 18 | LogLevel::Debug => println!("Debug: {}", message.green()), 19 | LogLevel::Info => println!("{}", message), 20 | LogLevel::Warning => println!("Warning: {}", message.yellow()), 21 | LogLevel::Error => println!("ERROR: {}", message.bright_red()), 22 | }; 23 | } 24 | 25 | unsafe fn from_c_string<'t>(string: *const u8, string_len: usize) -> &'t str { 26 | let slice = std::slice::from_raw_parts(string, string_len); 27 | std::str::from_utf8(slice as &[u8]).unwrap() 28 | } 29 | 30 | /// Print a debug message using the clooooggg 31 | /// 32 | /// # Safety 33 | /// 34 | /// message must be a valid pointer to utf-8 encoded data of size message_len 35 | #[no_mangle] 36 | pub unsafe extern "C" fn clog_debug(message: *const u8, message_len: usize) { 37 | clog(LogLevel::Debug, from_c_string(message, message_len)); 38 | } 39 | 40 | /// Print a message using the clooooggg 41 | /// 42 | /// # Safety 43 | /// 44 | /// message must be a valid pointer to utf-8 encoded data of size message_len 45 | #[no_mangle] 46 | pub unsafe extern "C" fn clog_info(message: *const u8, message_len: usize) { 47 | clog(LogLevel::Info, from_c_string(message, message_len)); 48 | } 49 | 50 | /// Print a warning message using the clooooggg 51 | /// 52 | /// # Safety 53 | /// 54 | /// message must be a valid pointer to utf-8 encoded data of size message_len 55 | #[no_mangle] 56 | pub unsafe extern "C" fn clog_warning(message: *const u8, message_len: usize) { 57 | clog(LogLevel::Warning, from_c_string(message, message_len)); 58 | } 59 | 60 | /// Print an error message using the clooooggg 61 | /// 62 | /// # Safety 63 | /// 64 | /// message must be a valid pointer to utf-8 encoded data of size message_len 65 | #[no_mangle] 66 | pub unsafe extern "C" fn clog_error(message: *const u8, message_len: usize) { 67 | clog(LogLevel::Error, from_c_string(message, message_len)); 68 | } 69 | 70 | #[cfg(test)] 71 | mod tests { 72 | /// faux test to demonstrate running rust unit tests through CMake / CTest 73 | #[test] 74 | fn test_colorlog() { 75 | assert_eq!(2 + 2, 4); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Build Test 2 | 3 | # Controls when the action will run. Triggers the workflow on push or pull request 4 | # events but only for the main branch 5 | on: 6 | push: 7 | branches: [main] 8 | pull_request: 9 | branches: [main] 10 | 11 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 12 | jobs: 13 | build_and_test: 14 | name: "${{ matrix.os }}: build and test" 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | os: [ubuntu-latest, macos-latest] 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | 24 | - name: rust-toolchain 25 | uses: actions-rs/toolchain@v1.0.6 26 | with: 27 | toolchain: stable-x86_64-unknown-linux-gnu 28 | 29 | - name: get-cmake 30 | uses: lukka/get-cmake@latest 31 | 32 | - name: Build project 33 | working-directory: "${{ runner.workspace }}/" 34 | run: | 35 | cmake -B ./build -S ./cmake-rust-demo -D CMAKE_INSTALL_PREFIX=${{ runner.workspace }}/install 36 | cmake --build ./build 37 | 38 | - name: Run tests 39 | working-directory: "${{ runner.workspace }}/build/" 40 | run: | 41 | ctest -VV 42 | 43 | - name: Install project 44 | working-directory: "${{ runner.workspace }}/" 45 | run: | 46 | cmake --build ./build --target install 47 | 48 | - name: Run the C app 49 | run: | 50 | ${{ runner.workspace }}/install/bin/app_c 51 | 52 | - name: Run the Rust app 53 | run: | 54 | ${{ runner.workspace }}/install/bin/app_rust 55 | 56 | build_and_test_windows: 57 | name: "windows-latest: build and test" 58 | runs-on: windows-latest 59 | 60 | steps: 61 | - uses: actions/checkout@v2 62 | 63 | - name: rust-toolchain 64 | uses: actions-rs/toolchain@v1.0.6 65 | with: 66 | toolchain: stable-x86_64-unknown-linux-gnu 67 | 68 | - name: get-cmake 69 | uses: lukka/get-cmake@latest 70 | 71 | - name: Build project 72 | working-directory: "${{ runner.workspace }}/" 73 | run: | 74 | cmake -B ./build -S ./cmake-rust-demo -A x64 -D CMAKE_INSTALL_PREFIX=${{ runner.workspace }}/install 75 | cmake --build ./build 76 | 77 | - name: Run tests 78 | working-directory: "${{ runner.workspace }}/build/" 79 | run: | 80 | ctest -VV -C Debug 81 | 82 | - name: Install project 83 | working-directory: "${{ runner.workspace }}/" 84 | run: | 85 | cmake --build ./build --target install 86 | 87 | - name: Run the C app 88 | run: | 89 | ${{ runner.workspace }}\\install\\bin\\app_c.exe 90 | 91 | - name: Run the Rust app 92 | run: | 93 | ${{ runner.workspace }}\\install\\bin\\app_rust.exe 94 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | AccessModifierOffset: -2 4 | AlignAfterOpenBracket: Align 5 | AlignConsecutiveMacros: false 6 | AlignConsecutiveAssignments: true 7 | AlignConsecutiveBitFields: false 8 | AlignConsecutiveDeclarations: false 9 | AlignEscapedNewlines: Left 10 | AlignOperands: Align 11 | AlignTrailingComments: true 12 | AllowAllArgumentsOnNextLine: true 13 | AllowAllConstructorInitializersOnNextLine: true 14 | AllowAllParametersOfDeclarationOnNextLine: true 15 | AllowShortEnumsOnASingleLine: true 16 | AllowShortBlocksOnASingleLine: Never 17 | AllowShortCaseLabelsOnASingleLine: false 18 | AllowShortFunctionsOnASingleLine: Empty 19 | AllowShortLambdasOnASingleLine: All 20 | AllowShortIfStatementsOnASingleLine: WithoutElse 21 | AllowShortLoopsOnASingleLine: true 22 | AlwaysBreakAfterDefinitionReturnType: None 23 | AlwaysBreakAfterReturnType: None 24 | AlwaysBreakBeforeMultilineStrings: false 25 | AlwaysBreakTemplateDeclarations: MultiLine 26 | BinPackArguments: true 27 | BinPackParameters: true 28 | BraceWrapping: 29 | AfterCaseLabel: false 30 | AfterClass: true 31 | AfterControlStatement: Never 32 | AfterEnum: false 33 | AfterFunction: true 34 | AfterNamespace: true 35 | AfterObjCDeclaration: false 36 | AfterStruct: false 37 | AfterUnion: false 38 | AfterExternBlock: false 39 | BeforeCatch: false 40 | BeforeElse: false 41 | BeforeLambdaBody: false 42 | BeforeWhile: false 43 | IndentBraces: false 44 | SplitEmptyFunction: true 45 | SplitEmptyRecord: true 46 | SplitEmptyNamespace: true 47 | BreakBeforeBinaryOperators: None 48 | BreakBeforeBraces: Linux 49 | BreakBeforeInheritanceComma: false 50 | BreakInheritanceList: BeforeColon 51 | BreakBeforeTernaryOperators: true 52 | BreakConstructorInitializersBeforeComma: false 53 | BreakConstructorInitializers: BeforeColon 54 | BreakAfterJavaFieldAnnotations: false 55 | BreakStringLiterals: true 56 | ColumnLimit: 0 57 | CommentPragmas: '^ IWYU pragma:' 58 | CompactNamespaces: false 59 | ConstructorInitializerAllOnOneLineOrOnePerLine: false 60 | ConstructorInitializerIndentWidth: 4 61 | ContinuationIndentWidth: 4 62 | Cpp11BracedListStyle: true 63 | DeriveLineEnding: true 64 | DerivePointerAlignment: true 65 | DisableFormat: false 66 | ExperimentalAutoDetectBinPacking: false 67 | FixNamespaceComments: true 68 | ForEachMacros: 69 | - foreach 70 | - Q_FOREACH 71 | - BOOST_FOREACH 72 | IncludeBlocks: Preserve 73 | IncludeCategories: 74 | - Regex: '^"(llvm|llvm-c|clang|clang-c)/' 75 | Priority: 2 76 | SortPriority: 0 77 | - Regex: '^(<|"(gtest|gmock|isl|json)/)' 78 | Priority: 3 79 | SortPriority: 0 80 | - Regex: '.*' 81 | Priority: 1 82 | SortPriority: 0 83 | IncludeIsMainRegex: '(Test)?$' 84 | IncludeIsMainSourceRegex: '' 85 | IndentCaseLabels: true 86 | IndentCaseBlocks: false 87 | IndentGotoLabels: true 88 | IndentPPDirectives: None 89 | IndentExternBlock: AfterExternBlock 90 | IndentWidth: 4 91 | IndentWrappedFunctionNames: false 92 | InsertTrailingCommas: None 93 | JavaScriptQuotes: Leave 94 | JavaScriptWrapImports: true 95 | KeepEmptyLinesAtTheStartOfBlocks: true 96 | MacroBlockBegin: '' 97 | MacroBlockEnd: '' 98 | MaxEmptyLinesToKeep: 1 99 | NamespaceIndentation: None 100 | ObjCBinPackProtocolList: Auto 101 | ObjCBlockIndentWidth: 2 102 | ObjCBreakBeforeNestedBlockParam: true 103 | ObjCSpaceAfterProperty: false 104 | ObjCSpaceBeforeProtocolList: true 105 | PenaltyBreakAssignment: 2 106 | PenaltyBreakBeforeFirstCallParameter: 19 107 | PenaltyBreakComment: 300 108 | PenaltyBreakFirstLessLess: 120 109 | PenaltyBreakString: 1000 110 | PenaltyBreakTemplateDeclaration: 10 111 | PenaltyExcessCharacter: 1000000 112 | PenaltyReturnTypeOnItsOwnLine: 60 113 | PointerAlignment: Right 114 | ReflowComments: true 115 | SortIncludes: false 116 | SortUsingDeclarations: true 117 | SpaceAfterCStyleCast: false 118 | SpaceAfterLogicalNot: false 119 | SpaceAfterTemplateKeyword: true 120 | SpaceBeforeAssignmentOperators: true 121 | SpaceBeforeCpp11BracedList: false 122 | SpaceBeforeCtorInitializerColon: true 123 | SpaceBeforeInheritanceColon: true 124 | SpaceBeforeParens: ControlStatements 125 | SpaceBeforeRangeBasedForLoopColon: true 126 | SpaceInEmptyBlock: false 127 | SpaceInEmptyParentheses: false 128 | SpacesBeforeTrailingComments: 1 129 | SpacesInAngles: false 130 | SpacesInConditionalStatement: false 131 | SpacesInContainerLiterals: true 132 | SpacesInCStyleCastParentheses: false 133 | SpacesInParentheses: false 134 | SpacesInSquareBrackets: false 135 | SpaceBeforeSquareBrackets: false 136 | Standard: Latest 137 | StatementMacros: 138 | - Q_UNUSED 139 | - QT_REQUIRE_VERSION 140 | TabWidth: 8 141 | UseCRLF: false 142 | UseTab: Never 143 | WhitespaceSensitiveMacros: 144 | - STRINGIZE 145 | - PP_STRINGIZE 146 | - BOOST_PP_STRINGIZE 147 | ... 148 | 149 | -------------------------------------------------------------------------------- /app_rust/build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::path::{Path, PathBuf}; 3 | 4 | use bindgen::builder; 5 | 6 | // A list of environment variables to query to determine additional libraries 7 | // that need to be linked to resolve dependencies. 8 | const LIB_ENV_LINK: &[&str] = &["LIBDEMO"]; 9 | 10 | // Additional [verbatim] libraries to link on Windows platforms 11 | const LIB_LINK_WINDOWS: &[&str] = &["wsock32", "ws2_32", "Shell32", "User32"]; 12 | 13 | // Generate bindings for these functions: 14 | const BINDGEN_FUNCTIONS: &[&str] = &["do_the_thing"]; 15 | 16 | // Generate bindings for these types (structs, enums): 17 | const BINDGEN_TYPES: &[&str] = &[]; 18 | 19 | // Find the required functions and types in these headers: 20 | const BINDGEN_HEADERS: &[&str] = &["../c/dostuff.h"]; 21 | 22 | // Find the required headers in these directories: 23 | const BINDGEN_INCLUDE_PATHS: &[&str] = &["-I../lib/c"]; 24 | 25 | // Write the bindings to this file: 26 | const BINDGEN_OUTPUT_FILE: &str = "src/sys.rs"; 27 | 28 | // Environment variable name prefixes worth including for diags 29 | const ENV_PATTERNS: &[&str] = &["CARGO_", "RUST", "LIB"]; 30 | 31 | fn main() -> Result<(), &'static str> { 32 | eprintln!("build.rs command line: {:?}", std::env::args()); 33 | eprintln!("Environment:"); 34 | std::env::vars() 35 | .filter(|(k, _)| ENV_PATTERNS.iter().any(|prefix| k.starts_with(prefix))) 36 | .for_each(|(k, v)| eprintln!(" {}={:?}", k, v)); 37 | 38 | // We only want to generate bindings for `cargo build`, not `cargo test`. 39 | // FindRust.cmake defines $CARGO_CMD so we can differentiate. 40 | let cargo_cmd = env::var("CARGO_CMD").unwrap_or_else(|_| "".into()); 41 | 42 | match cargo_cmd.as_str() { 43 | "build" => { 44 | println!("cargo:rerun-if-env-changed=LIBDEMO"); 45 | 46 | // Generate bindings as a part of the build. 47 | 48 | let maintainer_mode = env::var("MAINTAINER_MODE").unwrap_or_else(|_| "".into()); 49 | if maintainer_mode == "ON" { 50 | // Only generate the `.rs` bindings when maintainer-mode is enabled. 51 | // Bindgen requires libclang, which may not readily available, so we will commit the 52 | // bindings to version control and use maintainer-mode to update them, as needed. 53 | // On the plus-side, this means that our `.rs` file is present before our first build, 54 | // so at least rust-analyzer will be happy. 55 | generate_rust_bindings()?; 56 | } 57 | 58 | // Link executable with library dependencies. 59 | for var in LIB_ENV_LINK { 60 | if !search_and_link_lib(var)? { 61 | eprintln!("Undefined library dependency environment variable: {}", var); 62 | return Err("Undefined library dependency environment variable"); 63 | } 64 | } 65 | 66 | if cfg!(windows) { 67 | for lib in LIB_LINK_WINDOWS { 68 | println!("cargo:rustc-link-lib={}", lib); 69 | } 70 | } 71 | } 72 | 73 | _ => { 74 | return Ok(()); 75 | } 76 | } 77 | 78 | Ok(()) 79 | } 80 | 81 | /// Use bindgen to generate Rust bindings to call into C libraries. 82 | fn generate_rust_bindings() -> Result<(), &'static str> { 83 | let build_dir = PathBuf::from(env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| ".".into())); 84 | let build_include_path = format!("-I{}", build_dir.join(".").to_str().unwrap()); 85 | 86 | // Configure and generate bindings. 87 | let mut builder = builder() 88 | // Silence code-style warnings for generated bindings. 89 | .raw_line("#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]") 90 | // Make the bindings pretty. 91 | .rustfmt_bindings(true) 92 | // Disable the layout tests because we're committing `sys.rs` to source control. 93 | // Pointer width, integer size, etc. are probably not the same when generated as when compiled. 94 | .layout_tests(false) 95 | // Enable bindgen to find generated headers in the build directory, too. 96 | .clang_arg(build_include_path); 97 | 98 | for &include_path in BINDGEN_INCLUDE_PATHS { 99 | builder = builder.clang_arg(include_path); 100 | } 101 | for &header in BINDGEN_HEADERS { 102 | builder = builder.header(header); 103 | } 104 | for &c_function in BINDGEN_FUNCTIONS { 105 | builder = builder.allowlist_function(c_function); 106 | } 107 | for &c_type in BINDGEN_TYPES { 108 | builder = builder.allowlist_type(c_type); 109 | } 110 | 111 | // Generate! 112 | builder 113 | .generate() 114 | .expect("Unable to generate Rust bindings for C code") 115 | .write_to_file(BINDGEN_OUTPUT_FILE) 116 | .expect("Failed to write Rust bindings to output file"); 117 | 118 | eprintln!("bindgen outputting \"{}\"", BINDGEN_OUTPUT_FILE); 119 | 120 | Ok(()) 121 | } 122 | 123 | /// Return whether the specified environment variable has been set, and output 124 | /// linking directives as a side-effect 125 | fn search_and_link_lib(environment_variable: &str) -> Result { 126 | eprintln!(" - checking for {:?} in environment", environment_variable); 127 | let filepath_str = match env::var(environment_variable) { 128 | Err(env::VarError::NotPresent) => return Ok(false), 129 | Err(env::VarError::NotUnicode(_)) => return Err("environment value not unicode"), 130 | Ok(s) => { 131 | if s.is_empty() { 132 | return Ok(false); 133 | } else { 134 | s 135 | } 136 | } 137 | }; 138 | 139 | let parsed_path = parse_lib_path(&filepath_str)?; 140 | eprintln!( 141 | " - adding {:?} to rustc library search path", 142 | &parsed_path.dir 143 | ); 144 | println!("cargo:rustc-link-search={}", parsed_path.dir); 145 | eprintln!(" - requesting that rustc link {:?}", &parsed_path.libname); 146 | println!("cargo:rustc-link-lib={}", parsed_path.libname); 147 | 148 | Ok(true) 149 | } 150 | 151 | /// Struct to store a lib name and directory. 152 | /// Not the 153 | struct ParsedLibraryPath { 154 | dir: String, 155 | libname: String, 156 | } 157 | 158 | /// Parse a library path, returning: 159 | /// - the directory containing the library 160 | /// - the portion expected after the `-l` 161 | fn parse_lib_path<'a>(path: &'a str) -> Result { 162 | let path = PathBuf::from(path); 163 | let file_name = path 164 | .file_name() 165 | .ok_or("file name not found")? 166 | .to_str() 167 | .ok_or("file name not unicode")?; 168 | 169 | // This can't fail because it came from a &str 170 | let dir = path 171 | .parent() 172 | .unwrap_or_else(|| Path::new(".")) 173 | .to_str() 174 | .unwrap() 175 | .to_owned(); 176 | 177 | // Grab the portion up to the first '.' 178 | let full_libname = file_name 179 | .split('.') 180 | .next() 181 | .ok_or("no '.' found in file name")?; 182 | 183 | let libname = if !cfg!(windows) { 184 | // Trim off the "lib" for Linux/Unix systems 185 | full_libname 186 | .strip_prefix("lib") 187 | .ok_or(r#"file name doesn't begin with "lib""#)? 188 | } else { 189 | // Keep the full libname on Windows. 190 | full_libname 191 | } 192 | .to_owned(); 193 | 194 | Ok(ParsedLibraryPath { dir, libname }) 195 | } 196 | -------------------------------------------------------------------------------- /lib/rust/build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::path::{Path, PathBuf}; 3 | 4 | use bindgen::builder; 5 | 6 | // A list of environment variables to query to determine additional libraries 7 | // that need to be linked to resolve dependencies. 8 | const LIB_ENV_LINK: &[&str] = &["LIBDEMO"]; 9 | 10 | // Additional [verbatim] libraries to link on Windows platforms 11 | const LIB_LINK_WINDOWS: &[&str] = &["wsock32", "ws2_32", "Shell32", "User32"]; 12 | 13 | // Generate bindings for these functions: 14 | const BINDGEN_FUNCTIONS: &[&str] = &["do_the_thing"]; 15 | 16 | // Generate bindings for these types (structs, enums): 17 | const BINDGEN_TYPES: &[&str] = &[]; 18 | 19 | // Find the required functions and types in these headers: 20 | const BINDGEN_HEADERS: &[&str] = &["../c/dostuff.h"]; 21 | 22 | // Find the required headers in these directories: 23 | const BINDGEN_INCLUDE_PATHS: &[&str] = &["-I../c"]; 24 | 25 | // Write the bindings to this file: 26 | const BINDGEN_OUTPUT_FILE: &str = "src/sys.rs"; 27 | 28 | const C_HEADER_OUTPUT: &str = "demo-rust.h"; 29 | 30 | // Environment variable name prefixes worth including for diags 31 | const ENV_PATTERNS: &[&str] = &["CARGO_", "RUST", "LIB"]; 32 | 33 | fn main() -> Result<(), &'static str> { 34 | eprintln!("build.rs command line: {:?}", std::env::args()); 35 | eprintln!("Environment:"); 36 | std::env::vars() 37 | .filter(|(k, _)| ENV_PATTERNS.iter().any(|prefix| k.starts_with(prefix))) 38 | .for_each(|(k, v)| eprintln!(" {}={:?}", k, v)); 39 | 40 | // We only want to generate bindings for `cargo build`, not `cargo test`. 41 | // FindRust.cmake defines $CARGO_CMD so we can differentiate. 42 | let cargo_cmd = env::var("CARGO_CMD").unwrap_or_else(|_| "".into()); 43 | 44 | // If this environmment variable chnages, we should re-run this script. 45 | println!("cargo:rerun-if-env-changed=LIBDEMO"); 46 | 47 | match cargo_cmd.as_str() { 48 | "build" => { 49 | // Generate bindings as a part of the build. 50 | 51 | // Always generate the C-headers when CMake kicks off a build. 52 | generate_c_bindings()?; 53 | 54 | let maintainer_mode = env::var("MAINTAINER_MODE").unwrap_or_else(|_| "".into()); 55 | if maintainer_mode == "ON" { 56 | // Only generate the `.rs` bindings when maintainer-mode is enabled. 57 | // Bindgen requires libclang, which may not readily available, so we will commit the 58 | // bindings to version control and use maintainer-mode to update them, as needed. 59 | // On the plus-side, this means that our `.rs` file is present before our first build, 60 | // so at least rust-analyzer will be happy. 61 | generate_rust_bindings()?; 62 | } 63 | } 64 | 65 | "test" => { 66 | // Link test executable with library dependencies. 67 | for var in LIB_ENV_LINK { 68 | if !search_and_link_lib(var)? { 69 | eprintln!("Undefined library dependency environment variable: {}", var); 70 | return Err("Undefined library dependency environment variable"); 71 | } 72 | } 73 | 74 | if cfg!(windows) { 75 | for lib in LIB_LINK_WINDOWS { 76 | println!("cargo:rustc-link-lib={}", lib); 77 | } 78 | } 79 | } 80 | 81 | _ => { 82 | return Ok(()); 83 | } 84 | } 85 | 86 | Ok(()) 87 | } 88 | 89 | /// Use bindgen to generate Rust bindings to call into C libraries. 90 | fn generate_rust_bindings() -> Result<(), &'static str> { 91 | let build_dir = PathBuf::from(env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| ".".into())); 92 | let build_include_path = format!("-I{}", build_dir.join(".").to_str().unwrap()); 93 | 94 | // Configure and generate bindings. 95 | let mut builder = builder() 96 | // Silence code-style warnings for generated bindings. 97 | .raw_line("#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]") 98 | // Make the bindings pretty. 99 | .rustfmt_bindings(true) 100 | // Disable the layout tests because we're committing `sys.rs` to source control. 101 | // Pointer width, integer size, etc. are probably not the same when generated as when compiled. 102 | .layout_tests(false) 103 | // Enable bindgen to find generated headers in the build directory, too. 104 | .clang_arg(build_include_path); 105 | 106 | for &include_path in BINDGEN_INCLUDE_PATHS { 107 | builder = builder.clang_arg(include_path); 108 | } 109 | for &header in BINDGEN_HEADERS { 110 | builder = builder.header(header); 111 | } 112 | for &c_function in BINDGEN_FUNCTIONS { 113 | builder = builder.allowlist_function(c_function); 114 | } 115 | for &c_type in BINDGEN_TYPES { 116 | builder = builder.allowlist_type(c_type); 117 | } 118 | 119 | // Generate! 120 | builder 121 | .generate() 122 | .expect("Unable to generate Rust bindings for C code") 123 | .write_to_file(BINDGEN_OUTPUT_FILE) 124 | .expect("Failed to write Rust bindings to output file"); 125 | 126 | eprintln!("bindgen outputting \"{}\"", BINDGEN_OUTPUT_FILE); 127 | 128 | Ok(()) 129 | } 130 | 131 | /// Use cbindgen to generate C-headers for Rust library. 132 | fn generate_c_bindings() -> Result<(), &'static str> { 133 | let crate_dir = env::var("CARGO_MANIFEST_DIR").or(Err("CARGO_MANIFEST_DIR not specified"))?; 134 | let build_dir = PathBuf::from(env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| ".".into())); 135 | let outfile_path = build_dir.join(C_HEADER_OUTPUT); 136 | 137 | // Useful for build diagnostics 138 | eprintln!("cbindgen outputting {:?}", &outfile_path); 139 | cbindgen::generate(crate_dir) 140 | .expect("Unable to generate C headers for Rust code") 141 | .write_to_file(&outfile_path); 142 | 143 | Ok(()) 144 | } 145 | 146 | /// Return whether the specified environment variable has been set, and output 147 | /// linking directives as a side-effect 148 | fn search_and_link_lib(environment_variable: &str) -> Result { 149 | eprintln!(" - checking for {:?} in environment", environment_variable); 150 | let filepath_str = match env::var(environment_variable) { 151 | Err(env::VarError::NotPresent) => return Ok(false), 152 | Err(env::VarError::NotUnicode(_)) => return Err("environment value not unicode"), 153 | Ok(s) => { 154 | if s.is_empty() { 155 | return Ok(false); 156 | } else { 157 | s 158 | } 159 | } 160 | }; 161 | 162 | let parsed_path = parse_lib_path(&filepath_str)?; 163 | eprintln!( 164 | " - adding {:?} to rustc library search path", 165 | &parsed_path.dir 166 | ); 167 | println!("cargo:rustc-link-search={}", parsed_path.dir); 168 | eprintln!(" - requesting that rustc link {:?}", &parsed_path.libname); 169 | println!("cargo:rustc-link-lib={}", parsed_path.libname); 170 | 171 | Ok(true) 172 | } 173 | 174 | /// Struct to store a lib name and directory. 175 | /// Not the 176 | struct ParsedLibraryPath { 177 | dir: String, 178 | libname: String, 179 | } 180 | 181 | /// Parse a library path, returning: 182 | /// - the directory containing the library 183 | /// - the portion expected after the `-l` 184 | fn parse_lib_path<'a>(path: &'a str) -> Result { 185 | let path = PathBuf::from(path); 186 | let file_name = path 187 | .file_name() 188 | .ok_or("file name not found")? 189 | .to_str() 190 | .ok_or("file name not unicode")?; 191 | 192 | // This can't fail because it came from a &str 193 | let dir = path 194 | .parent() 195 | .unwrap_or_else(|| Path::new(".")) 196 | .to_str() 197 | .unwrap() 198 | .to_owned(); 199 | 200 | // Grab the portion up to the first '.' 201 | let full_libname = file_name 202 | .split('.') 203 | .next() 204 | .ok_or("no '.' found in file name")?; 205 | 206 | let libname = if !cfg!(windows) { 207 | // Trim off the "lib" for Linux/Unix systems 208 | full_libname 209 | .strip_prefix("lib") 210 | .ok_or(r#"file name doesn't begin with "lib""#)? 211 | } else { 212 | // Keep the full libname on Windows. 213 | full_libname 214 | } 215 | .to_owned(); 216 | 217 | Ok(ParsedLibraryPath { dir, libname }) 218 | } 219 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CMake Rust Demo 2 | 3 | ![Build Test](https://github.com/micahsnyder/cmake-rust-demo/workflows/Build%20Test/badge.svg) 4 | 5 | A C CMake demo using Rust static library components and building Rust executables. 6 | The notable feature of this project is [cmake/FindRust.cmake](cmake/FindRust.cmake) 7 | 8 | ## Usage 9 | 10 | Add `FindRust.cmake` to your project's `cmake` directory and use the following to enable Rust support: 11 | 12 | ```cmake 13 | find_package(Rust REQUIRED) 14 | ``` 15 | 16 | ### Rust-based C-style Static Libraries 17 | 18 | To build a rust library and link it into your app, use: 19 | 20 | ```cmake 21 | add_rust_library(TARGET yourlib 22 | SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 23 | BINARY_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" 24 | ) 25 | 26 | add_executable(yourexe) 27 | target_sources(yourexe PRIVATE yourexe.c) 28 | target_link_libraries(yourexe yourlib) 29 | ``` 30 | 31 | ### Rust Library Unit Tests 32 | 33 | For unit test support, you can use the `add_rust_test()` function, like this: 34 | 35 | ```cmake 36 | add_rust_library(TARGET yourlib 37 | SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 38 | BINARY_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" 39 | ) 40 | add_rust_test(NAME yourlib 41 | SOURCE_DIRECTORY "${CMAKE_SOURCE_DIR}/path/to/yourlib" 42 | BINARY_DIRECTORY "${CMAKE_BINARY_DIR}/path/to/yourlib" 43 | ) 44 | ``` 45 | 46 | And don't forget to enable CTest early in your top-level `CMakeLists.txt` file: 47 | 48 | ```cmake 49 | # Enable CTest 50 | if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) 51 | include(CTest) 52 | enable_testing() 53 | endif() 54 | ``` 55 | 56 | ### Rust-based Executables 57 | 58 | To build a rust executable use: 59 | 60 | ```cmake 61 | add_rust_executable(TARGET yourexe 62 | SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 63 | BINARY_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" 64 | ) 65 | add_executable(YourProject::yourexe ALIAS yourexe) 66 | ``` 67 | 68 | ## Minimum Rust version 69 | 70 | You may set the CMake variable `RUSTC_MINIMUM_REQUIRED` to enforce a minimum Rust version, such as "1.56" for the 2021 edition support. 71 | 72 | ## `cbindgen` and `bindgen` FFI generation 73 | 74 | This project demonstrates using `bindgen` and `cbindgen` within the `/lib/rust/build.rs` script to generate the API's at build time. 75 | 76 | `cbindgen` is used to generate a `demorust.h` C binding for the Rust exports every time you build. It'll be dropped in the build directory. 77 | 78 | `bindgen`, on the otherhand, generates a `sys.rs` Rust binding for the C exports required by the Rust code. Unfortunately, `bindgen` depends on libclang for some features that aren't readily available on all systems. So we only run `bindgen` if you set the `MAINTAINER_MODE` CMake parameter to `ON`. That works out okay, as the `sys.rs` file is dropped into the source directory, not the build directory. But that means you have to remember to build with `MAINTAINER_MODE=ON` any time you change the internal C API's used by the Rust library. 79 | 80 | The `cbindgen` and `bindgen` programs don't need to be pre-installed. `Cargo.toml` will pull them in during the build. 81 | 82 | ## Building this project 83 | 84 | Requirements: 85 | - CMake 3.18+ 86 | - The Rust toolchain (Cargo, etc) 87 | 88 | Run: 89 | ```bash 90 | mkdir build && cd build 91 | cmake .. \ 92 | -D MAINTAINER_MODE=ON \ 93 | -D CMAKE_INSTALL_PREFIX=install 94 | cmake --build . 95 | ctest -V 96 | cmake --build . --target install 97 | ``` 98 | 99 | ## Vendoring dependencies 100 | 101 | For building a source package with CPack (E.g., the `TGZ` package archive generator), you may wish to vendor the Cargo dependencies so your users can do offline builds when using your source package. 102 | 103 | The `FindRust.cmake` module makes that easy. Simply define `VENDOR_DEPENDENCIES=ON` and it will run `cargo vendor` during the configuration stage. The dependencies and assocaited `config.toml` file, instructing cargo to use the vendored dependencies, will be placed in a `.cargo` directory next to each of your `Cargo.toml` files. 104 | 105 | Example building a source tarball with vendored dependencies: 106 | ```bash 107 | mkdir build && cd build 108 | cmake .. -D VENDOR_DEPENDENCIES=ON && cpack --config CPackSourceConfig.cmake 109 | ``` 110 | 111 | Afterwards, you should have a source package (E.g., `cmake-rust-0.1.0.tar.gz`) containing the project with vendored dependencies in your working directory, and if you run `git status`, you'll see the `.cargo` directories: 112 | ```bash 113 | Untracked files: 114 | (use "git add ..." to include in what will be committed) 115 | ../common/gen_uuid/.cargo/ 116 | ../lib/colorlog/.cargo/ 117 | ``` 118 | 119 | At this point you could do something like this, to see it build w/out downloading the crates: 120 | ```bash 121 | tar xzf cmake-rust-0.1.0.tar.gz 122 | cd cmake-rust-0.1.0 123 | mkdir build && cd build 124 | cmake .. && cmake --build . && ctest 125 | ``` 126 | 127 | You'll note that the vendored dependencies appear in your source directory. To remove them, you can do this: 128 | ```bash 129 | rm -rf **/.cargo 130 | ``` 131 | 132 | # Installing Rust binaries with CMake 133 | 134 | C static libraries don't link in other static libraries. Fully-static builds of projects that are composed of a few different static libraries will result in a collection of static libraries. If you're only providing an application, then you can link them into the app and only install the app. But if you provide a library for others to consume then you may need to install all of the static libraries that compose the features of "the library" you provide for downstream projects. 135 | 136 | For example, let's say you've got a C library that may be built as a shared lib AND as a static lib, and you're slowly porting the C code into a Rust static library. You will link your Rust static library into the C library to maintain the original C API for your downstream users. With a shared-build of the C library, the Rust static library will get linked into the shared library and the downstream users never have to know it exists. Buf for a static-build of the C library, the C library is linked *against* your Rust library but they remain two separate libs that must both be linked with the downstream applications. You will need to install both the C static library *and* the Rust static library. 137 | 138 | Projects built with CMake can use CMake to install the software directly (e.g. under `/usr/local`) or via a packager like WiX Toolset (Windows) or `.deb` / `.rpm` / `.pkg` packages. 139 | 140 | Rust binaries aren't treated quite the same by CMake as native C binaries, but you can use CMake to install them. 141 | 142 | ## How to install Rust binaries with CMake 143 | 144 | The first thing you'll probably need if you want to use CMake to install stuff, whether or not you bundle in some Rust binaries, is to include the GNUEInstallDirs module somewhere at the top of your top-level `CMakeLists.txt`: 145 | 146 | ```cmake 147 | include(GNUInstallDirs) 148 | ``` 149 | 150 | Now with a regular C library or executable CMake target, you might configure them for installation like this: 151 | ```cmake 152 | install(TARGETS demo DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) 153 | ``` 154 | or: 155 | ```cmake 156 | install(TARGETS app DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT programs) 157 | ``` 158 | 159 | Rust library CMake targets aren't normal CMake binary targets though. They're "custom" targets, which means you will instead have to use `install(FILES` instead of `install(TARGETS`, and then point CMake at the specific file you need installed instead of at a target. Our `FindRust.cmake`'s `add_rust_library()` function makes this easy. When you add a Rust library, it sets the target properties such that you can simply use CMake's `$` [generator expression](https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html) to provide the file path. 160 | 161 | In this demo, we configure installation for our `demorust` Rust static library like this: 162 | ```cmake 163 | install(FILES $ DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) 164 | ``` 165 | 166 | And for our `app_rust` Rust executable, we install like this: 167 | ```cmake 168 | get_target_property(app_rust_EXECUTABLE app_rust IMPORTED_LOCATION) 169 | install(PROGRAMS ${app_rust_EXECUTABLE} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT programs) 170 | ``` 171 | Note that we have to get the `IMPORTED_LOCATION` manually for the executable. 172 | 173 | ## License 174 | 175 | This project is dual-licensed under MIT and Apache 2.0. 176 | 177 | ## Contribute 178 | 179 | This project could use your help testing build support for various targets on various operating systems. 180 | Please feel free to help work on the outstanding issues too! 181 | -------------------------------------------------------------------------------- /LICENSE-Apache-2.0.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /cmake/FindRust.cmake: -------------------------------------------------------------------------------- 1 | # Find the Rust toolchain and add the `add_rust_library()` API to build Rust 2 | # libraries. 3 | # 4 | # Copyright (C) 2020-2022 Micah Snyder. 5 | # 6 | # Author: Micah Snyder 7 | # To see this in a sample project, visit: https://github.com/micahsnyder/cmake-rust-demo 8 | # 9 | # Code to set the Cargo arguments was lifted from: 10 | # https://github.com/Devolutions/CMakeRust 11 | # 12 | # This Module defines the following variables: 13 | # - _FOUND - True if the program was found 14 | # - _EXECUTABLE - path of the program 15 | # - _VERSION - version number of the program 16 | # 17 | # ... for the following Rust toolchain programs: 18 | # - cargo 19 | # - rustc 20 | # - rustup 21 | # - rust-gdb 22 | # - rust-lldb 23 | # - rustdoc 24 | # - rustfmt 25 | # - bindgen 26 | # 27 | # Callers can make any program mandatory by setting `_REQUIRED` before 28 | # the call to `find_package(Rust)` 29 | # 30 | # Eg: 31 | # find_package(Rust REQUIRED) 32 | # 33 | # This module provides the following functions: 34 | # ============================================= 35 | # 36 | # `add_rust_library()` 37 | # -------------------- 38 | # 39 | # This allows a caller to create a Rust static library 40 | # target which you can link to with `target_link_libraries()`. 41 | # 42 | # Your Rust static library target will itself depend on the native static libs 43 | # you get from `rustc --crate-type staticlib --print=native-static-libs /dev/null` 44 | # 45 | # The CARGO_CMD environment variable will be set to "BUILD" so you can tell 46 | # it's not building the unit tests inside your (optional) `build.rs` file. 47 | # 48 | # Example `add_rust_library()` usage: 49 | # 50 | # ```cmake 51 | # add_rust_library(TARGET yourlib 52 | # SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") 53 | # BINARY_DIRECTORY "${CMAKE_BINARY_DIR}") 54 | # add_library(YourProject::yourlib ALIAS yourlib) 55 | # 56 | # add_executable(yourexe) 57 | # target_link_libraries(yourexe YourProject::yourlib) 58 | # ``` 59 | # 60 | # If your library has unit tests AND your library does NOT depend on your C 61 | # librar(ies), you can use `add_rust_library()` to build your library and unit 62 | # tests at the same time. Just pass `PRECOMPILE_TESTS TRUE` to add_rust_library. 63 | # This should make it so when you run the tests, they don't have to compile 64 | # during the test run. 65 | # 66 | # If your library does have C dependencies, you can still precompile the tests 67 | # by passing `PRECOMPILE_TESTS TRUE`, with `add_rust_test()` instead. 68 | # It will be slower because it will have to compile the C stuff first, 69 | # then compile the Rust stuff from scratch. See below. 70 | # 71 | # `add_rust_test()` 72 | # ----------------- 73 | # 74 | # This allows a caller to run `cargo test` for a specific Rust target as a CTest 75 | # test. 76 | # 77 | # The CARGO_CMD environment variable will be set to "TEST" so you can tell 78 | # it's not building the unit tests inside your (optional) `build.rs` file. 79 | # 80 | # Example `add_rust_test()` usage: 81 | # 82 | # ```cmake 83 | # add_rust_test(NAME yourlib 84 | # SOURCE_DIRECTORY "${CMAKE_SOURCE_DIR}/path/to/yourlib" 85 | # BINARY_DIRECTORY "${CMAKE_BINARY_DIR}" 86 | # ) 87 | # set_property(TEST yourlib PROPERTY ENVIRONMENT ${ENVIRONMENT}) 88 | # ``` 89 | # 90 | # If your library has unit tests AND your library DOES depend on your C 91 | # libraries, you can precompile the unit tests application with some extra 92 | # parameters to `add_rust_test()`: 93 | # - `PRECOMPILE_TESTS TRUE` 94 | # - `DEPENDS ` 95 | # - `ENVIRONMENT ` 96 | # 97 | # The `DEPENDS` option is required so CMake will build the C library first. 98 | # The `ENVIRONMENT` option is required for use in your `build.rs` file so you 99 | # can tell rustc how to link to your C library. 100 | # 101 | # For example: 102 | # 103 | # ```cmake 104 | # add_rust_test(NAME yourlib 105 | # SOURCE_DIRECTORY "${CMAKE_SOURCE_DIR}/yourlib" 106 | # BINARY_DIRECTORY "${CMAKE_BINARY_DIR}" 107 | # PRECOMPILE_TESTS TRUE 108 | # DEPENDS ClamAV::libclamav 109 | # ENVIRONMENT "${ENVIRONMENT}" 110 | # ) 111 | # set_property(TEST yourlib PROPERTY ENVIRONMENT ${ENVIRONMENT}) 112 | # ``` 113 | # 114 | # `add_rust_executable()` 115 | # ----------------------- 116 | # 117 | # This allows a caller to create a Rust executable target. 118 | # 119 | # Example `add_rust_executable()` usage: 120 | # 121 | # ```cmake 122 | # add_rust_executable(TARGET yourexe 123 | # SOURCE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 124 | # BINARY_DIRECTORY "${CMAKE_BINARY_DIR}" 125 | # ) 126 | # add_executable(YourProject::yourexe ALIAS yourexe) 127 | # ``` 128 | 129 | if(NOT DEFINED CARGO_HOME) 130 | if(WIN32) 131 | set(CARGO_HOME "$ENV{USERPROFILE}/.cargo") 132 | else() 133 | set(CARGO_HOME "$ENV{HOME}/.cargo") 134 | endif() 135 | endif() 136 | 137 | include(FindPackageHandleStandardArgs) 138 | 139 | function(find_rust_program RUST_PROGRAM) 140 | find_program(${RUST_PROGRAM}_EXECUTABLE ${RUST_PROGRAM} 141 | HINTS "${CARGO_HOME}" 142 | PATH_SUFFIXES "bin" 143 | ) 144 | 145 | if(${RUST_PROGRAM}_EXECUTABLE) 146 | execute_process(COMMAND "${${RUST_PROGRAM}_EXECUTABLE}" --version 147 | OUTPUT_VARIABLE ${RUST_PROGRAM}_VERSION_OUTPUT 148 | ERROR_VARIABLE ${RUST_PROGRAM}_VERSION_ERROR 149 | RESULT_VARIABLE ${RUST_PROGRAM}_VERSION_RESULT 150 | ) 151 | 152 | if(NOT ${${RUST_PROGRAM}_VERSION_RESULT} EQUAL 0) 153 | message(STATUS "Rust tool `${RUST_PROGRAM}` not found: Failed to determine version.") 154 | unset(${RUST_PROGRAM}_EXECUTABLE) 155 | else() 156 | string(REGEX 157 | MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?(-nightly)?" 158 | ${RUST_PROGRAM}_VERSION "${${RUST_PROGRAM}_VERSION_OUTPUT}" 159 | ) 160 | set(${RUST_PROGRAM}_VERSION "${${RUST_PROGRAM}_VERSION}" PARENT_SCOPE) 161 | message(STATUS "Rust tool `${RUST_PROGRAM}` found: ${${RUST_PROGRAM}_EXECUTABLE}, ${${RUST_PROGRAM}_VERSION}") 162 | endif() 163 | 164 | mark_as_advanced(${RUST_PROGRAM}_EXECUTABLE ${RUST_PROGRAM}_VERSION) 165 | else() 166 | if(${${RUST_PROGRAM}_REQUIRED}) 167 | message(FATAL_ERROR "Rust tool `${RUST_PROGRAM}` not found.") 168 | else() 169 | message(STATUS "Rust tool `${RUST_PROGRAM}` not found.") 170 | endif() 171 | endif() 172 | endfunction() 173 | 174 | function(cargo_vendor) 175 | set(options) 176 | set(oneValueArgs TARGET SOURCE_DIRECTORY BINARY_DIRECTORY) 177 | cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) 178 | 179 | if(NOT EXISTS ${ARGS_SOURCE_DIRECTORY}/.cargo/config.toml) 180 | # Vendor the dependencies and create .cargo/config.toml 181 | # Vendored dependencies will be used during the build. 182 | # This will allow us to package vendored dependencies in source tarballs 183 | # for online builds when we run `cpack --config CPackSourceConfig.cmake` 184 | message(STATUS "Running `cargo vendor` to collect dependencies for ${ARGS_TARGET}. This may take a while if the local crates.io index needs to be updated ...") 185 | make_directory(${ARGS_SOURCE_DIRECTORY}/.cargo) 186 | execute_process( 187 | COMMAND ${CMAKE_COMMAND} -E env "CARGO_TARGET_DIR=${ARGS_BINARY_DIRECTORY}" ${cargo_EXECUTABLE} vendor ".cargo/vendor" 188 | WORKING_DIRECTORY "${ARGS_SOURCE_DIRECTORY}" 189 | OUTPUT_VARIABLE CARGO_VENDOR_OUTPUT 190 | ERROR_VARIABLE CARGO_VENDOR_ERROR 191 | RESULT_VARIABLE CARGO_VENDOR_RESULT 192 | ) 193 | 194 | if(NOT ${CARGO_VENDOR_RESULT} EQUAL 0) 195 | message(FATAL_ERROR "Failed!\n${CARGO_VENDOR_ERROR}") 196 | else() 197 | message("Success!") 198 | endif() 199 | 200 | write_file(${ARGS_SOURCE_DIRECTORY}/.cargo/config.toml " 201 | [source.crates-io] 202 | replace-with = \"vendored-sources\" 203 | 204 | [source.vendored-sources] 205 | directory = \".cargo/vendor\" 206 | " 207 | ) 208 | endif() 209 | endfunction() 210 | 211 | function(add_rust_executable) 212 | set(options) 213 | set(oneValueArgs TARGET SOURCE_DIRECTORY BINARY_DIRECTORY) 214 | cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) 215 | 216 | if(WIN32) 217 | set(OUTPUT "${ARGS_BINARY_DIRECTORY}/${RUST_COMPILER_TARGET}/${CARGO_BUILD_TYPE}/${ARGS_TARGET}.exe") 218 | else() 219 | set(OUTPUT "${ARGS_BINARY_DIRECTORY}/${RUST_COMPILER_TARGET}/${CARGO_BUILD_TYPE}/${ARGS_TARGET}") 220 | endif() 221 | 222 | file(GLOB_RECURSE EXE_SOURCES "${ARGS_SOURCE_DIRECTORY}/*.rs") 223 | 224 | set(MY_CARGO_ARGS ${CARGO_ARGS}) 225 | list(APPEND MY_CARGO_ARGS "--target-dir" ${ARGS_BINARY_DIRECTORY}) 226 | list(JOIN MY_CARGO_ARGS " " MY_CARGO_ARGS_STRING) 227 | 228 | # Build the executable. 229 | add_custom_command( 230 | OUTPUT "${OUTPUT}" 231 | COMMAND ${CMAKE_COMMAND} -E env "CARGO_TARGET_DIR=${ARGS_BINARY_DIRECTORY}" ${cargo_EXECUTABLE} ARGS ${MY_CARGO_ARGS} 232 | WORKING_DIRECTORY "${ARGS_SOURCE_DIRECTORY}" 233 | DEPENDS ${EXE_SOURCES} 234 | COMMENT "Building ${ARGS_TARGET} in ${ARGS_BINARY_DIRECTORY} with:\n\t ${cargo_EXECUTABLE} ${MY_CARGO_ARGS_STRING}") 235 | 236 | # Create a target from the build output 237 | add_custom_target(${ARGS_TARGET}_target 238 | DEPENDS ${OUTPUT}) 239 | 240 | # Create an executable target from custom target 241 | add_custom_target(${ARGS_TARGET} ALL DEPENDS ${ARGS_TARGET}_target) 242 | 243 | # Specify where the executable is 244 | set_target_properties(${ARGS_TARGET} 245 | PROPERTIES 246 | IMPORTED_LOCATION "${OUTPUT}" 247 | ) 248 | 249 | # Vendor the dependencies, if desired 250 | if(VENDOR_DEPENDENCIES) 251 | cargo_vendor(TARGET "${ARGS_TARGET}" 252 | SOURCE_DIRECTORY "${ARGS_SOURCE_DIRECTORY}" 253 | BINARY_DIRECTORY "${ARGS_BINARY_DIRECTORY}" 254 | ) 255 | endif() 256 | endfunction() 257 | 258 | function(add_rust_library) 259 | set(options) 260 | set(oneValueArgs TARGET SOURCE_DIRECTORY BINARY_DIRECTORY PRECOMPILE_TESTS) 261 | cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) 262 | 263 | if(WIN32) 264 | set(OUTPUT "${ARGS_BINARY_DIRECTORY}/${RUST_COMPILER_TARGET}/${CARGO_BUILD_TYPE}/${ARGS_TARGET}.lib") 265 | else() 266 | set(OUTPUT "${ARGS_BINARY_DIRECTORY}/${RUST_COMPILER_TARGET}/${CARGO_BUILD_TYPE}/lib${ARGS_TARGET}.a") 267 | endif() 268 | 269 | file(GLOB_RECURSE LIB_SOURCES "${ARGS_SOURCE_DIRECTORY}/*.rs") 270 | 271 | set(MY_CARGO_ARGS ${CARGO_ARGS}) 272 | if(ARGS_PRECOMPILE_TESTS) 273 | list(APPEND MY_CARGO_ARGS "--tests") 274 | endif() 275 | list(APPEND MY_CARGO_ARGS "--target-dir" ${ARGS_BINARY_DIRECTORY}) 276 | list(JOIN MY_CARGO_ARGS " " MY_CARGO_ARGS_STRING) 277 | 278 | # Build the library and generate the c-binding 279 | if("${CMAKE_OSX_ARCHITECTURES}" MATCHES "^(arm64;x86_64|x86_64;arm64)$") 280 | add_custom_command( 281 | OUTPUT "${OUTPUT}" 282 | COMMAND ${CMAKE_COMMAND} -E env "CARGO_CMD=build" "CARGO_TARGET_DIR=${ARGS_BINARY_DIRECTORY}" "MAINTAINER_MODE=${MAINTAINER_MODE}" "RUSTFLAGS=\"${RUSTFLAGS}\"" ${cargo_EXECUTABLE} ARGS ${MY_CARGO_ARGS} --target=x86_64-apple-darwin 283 | COMMAND ${CMAKE_COMMAND} -E env "CARGO_CMD=build" "CARGO_TARGET_DIR=${ARGS_BINARY_DIRECTORY}" "MAINTAINER_MODE=${MAINTAINER_MODE}" "RUSTFLAGS=\"${RUSTFLAGS}\"" ${cargo_EXECUTABLE} ARGS ${MY_CARGO_ARGS} --target=aarch64-apple-darwin 284 | COMMAND ${CMAKE_COMMAND} -E make_directory "${ARGS_BINARY_DIRECTORY}/${RUST_COMPILER_TARGET}/${CARGO_BUILD_TYPE}" 285 | COMMAND lipo ARGS -create ${ARGS_BINARY_DIRECTORY}/x86_64-apple-darwin/${CARGO_BUILD_TYPE}/lib${ARGS_TARGET}.a ${ARGS_BINARY_DIRECTORY}/aarch64-apple-darwin/${CARGO_BUILD_TYPE}/lib${ARGS_TARGET}.a -output "${OUTPUT}" 286 | WORKING_DIRECTORY "${ARGS_SOURCE_DIRECTORY}" 287 | DEPENDS ${LIB_SOURCES} 288 | COMMENT "Building ${ARGS_TARGET} in ${ARGS_BINARY_DIRECTORY} with: ${cargo_EXECUTABLE} ${MY_CARGO_ARGS_STRING}") 289 | else() 290 | add_custom_command( 291 | OUTPUT "${OUTPUT}" 292 | COMMAND ${CMAKE_COMMAND} -E env "CARGO_CMD=build" "CARGO_TARGET_DIR=${ARGS_BINARY_DIRECTORY}" "MAINTAINER_MODE=${MAINTAINER_MODE}" "RUSTFLAGS=\"${RUSTFLAGS}\"" ${cargo_EXECUTABLE} ARGS ${MY_CARGO_ARGS} 293 | WORKING_DIRECTORY "${ARGS_SOURCE_DIRECTORY}" 294 | DEPENDS ${LIB_SOURCES} 295 | COMMENT "Building ${ARGS_TARGET} in ${ARGS_BINARY_DIRECTORY} with: ${cargo_EXECUTABLE} ${MY_CARGO_ARGS_STRING}") 296 | endif() 297 | 298 | # Create a target from the build output 299 | add_custom_target(${ARGS_TARGET}_target 300 | DEPENDS ${OUTPUT}) 301 | 302 | # Create a static imported library target from custom target 303 | add_library(${ARGS_TARGET} STATIC IMPORTED GLOBAL) 304 | add_dependencies(${ARGS_TARGET} ${ARGS_TARGET}_target) 305 | target_link_libraries(${ARGS_TARGET} INTERFACE ${RUST_NATIVE_STATIC_LIBS}) 306 | 307 | # Specify where the library is and where to find the headers 308 | set_target_properties(${ARGS_TARGET} 309 | PROPERTIES 310 | IMPORTED_LOCATION "${OUTPUT}" 311 | INTERFACE_INCLUDE_DIRECTORIES "${ARGS_SOURCE_DIRECTORY};${ARGS_BINARY_DIRECTORY}" 312 | ) 313 | 314 | # Vendor the dependencies, if desired 315 | if(VENDOR_DEPENDENCIES) 316 | cargo_vendor(TARGET "${ARGS_TARGET}" 317 | SOURCE_DIRECTORY "${ARGS_SOURCE_DIRECTORY}" 318 | BINARY_DIRECTORY "${ARGS_BINARY_DIRECTORY}") 319 | endif() 320 | endfunction() 321 | 322 | function(add_rust_test) 323 | set(options) 324 | set(oneValueArgs NAME SOURCE_DIRECTORY BINARY_DIRECTORY PRECOMPILE_TESTS DEPENDS) 325 | set(multiValueArgs ENVIRONMENT) 326 | cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) 327 | 328 | set(MY_CARGO_ARGS "test") 329 | 330 | if(NOT "${CMAKE_OSX_ARCHITECTURES}" MATCHES "^(arm64;x86_64|x86_64;arm64)$") # Don't specify the target for universal, we'll do that manually for each build. 331 | list(APPEND MY_CARGO_ARGS "--target" ${RUST_COMPILER_TARGET}) 332 | endif() 333 | 334 | if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") 335 | list(APPEND MY_CARGO_ARGS "--release") 336 | endif() 337 | 338 | list(APPEND MY_CARGO_ARGS "--target-dir" ${ARGS_BINARY_DIRECTORY}) 339 | list(JOIN MY_CARGO_ARGS " " MY_CARGO_ARGS_STRING) 340 | 341 | if(ARGS_PRECOMPILE_TESTS) 342 | list(APPEND ARGS_ENVIRONMENT "CARGO_CMD=test" "CARGO_TARGET_DIR=${ARGS_BINARY_DIRECTORY}") 343 | add_custom_target(${ARGS_NAME}_tests ALL 344 | COMMAND ${CMAKE_COMMAND} -E env ${ARGS_ENVIRONMENT} ${cargo_EXECUTABLE} ${MY_CARGO_ARGS} --color always --no-run 345 | DEPENDS ${ARGS_DEPENDS} 346 | WORKING_DIRECTORY ${ARGS_SOURCE_DIRECTORY} 347 | ) 348 | endif() 349 | 350 | add_test( 351 | NAME ${ARGS_NAME} 352 | COMMAND ${CMAKE_COMMAND} -E env "CARGO_CMD=test" "CARGO_TARGET_DIR=${ARGS_BINARY_DIRECTORY}" ${cargo_EXECUTABLE} ${MY_CARGO_ARGS} --color always 353 | WORKING_DIRECTORY ${ARGS_SOURCE_DIRECTORY} 354 | ) 355 | endfunction() 356 | 357 | # 358 | # Cargo is the primary tool for using the Rust Toolchain to to build static 359 | # libs that can include other crate dependencies. 360 | # 361 | find_rust_program(cargo) 362 | 363 | # These other programs may also be useful... 364 | find_rust_program(rustc) 365 | find_rust_program(rustup) 366 | find_rust_program(rust-gdb) 367 | find_rust_program(rust-lldb) 368 | find_rust_program(rustdoc) 369 | find_rust_program(rustfmt) 370 | find_rust_program(bindgen) 371 | 372 | if(RUSTC_MINIMUM_REQUIRED AND rustc_VERSION VERSION_LESS RUSTC_MINIMUM_REQUIRED) 373 | message(FATAL_ERROR "Your Rust toolchain is to old to build this project: 374 | ${rustc_VERSION} < ${RUSTC_MINIMUM_REQUIRED}") 375 | endif() 376 | 377 | # Determine the native libs required to link w/ rust static libs 378 | # message(STATUS "Detecting native static libs for rust: ${rustc_EXECUTABLE} --crate-type staticlib --print=native-static-libs /dev/null") 379 | execute_process( 380 | COMMAND ${CMAKE_COMMAND} -E env "CARGO_TARGET_DIR=${CMAKE_BINARY_DIR}" ${rustc_EXECUTABLE} --crate-type staticlib --print=native-static-libs /dev/null 381 | OUTPUT_VARIABLE RUST_NATIVE_STATIC_LIBS_OUTPUT 382 | ERROR_VARIABLE RUST_NATIVE_STATIC_LIBS_ERROR 383 | RESULT_VARIABLE RUST_NATIVE_STATIC_LIBS_RESULT 384 | ) 385 | string(REGEX REPLACE "\r?\n" ";" LINE_LIST "${RUST_NATIVE_STATIC_LIBS_ERROR}") 386 | 387 | foreach(LINE ${LINE_LIST}) 388 | # do the match on each line 389 | string(REGEX MATCH "native-static-libs: .*" LINE "${LINE}") 390 | 391 | if(NOT LINE) 392 | continue() 393 | endif() 394 | 395 | string(REPLACE "native-static-libs: " "" LINE "${LINE}") 396 | string(REGEX REPLACE " " "" LINE "${LINE}") 397 | string(REGEX REPLACE " " ";" LINE "${LINE}") 398 | 399 | if(LINE) 400 | message(STATUS "Rust's native static libs: ${LINE}") 401 | set(RUST_NATIVE_STATIC_LIBS "${LINE}") 402 | break() 403 | endif() 404 | endforeach() 405 | 406 | if(NOT RUST_COMPILER_TARGET) 407 | # Automatically determine the Rust Target Triple. 408 | # Note: Users may override automatic target detection by specifying their own. Most likely needed for cross-compiling. 409 | # For reference determining target platform: https://doc.rust-lang.org/nightly/rustc/platform-support.html 410 | if(WIN32) 411 | # For windows x86/x64, it's easy enough to guess the target. 412 | if(CMAKE_SIZEOF_VOID_P EQUAL 8) 413 | set(RUST_COMPILER_TARGET "x86_64-pc-windows-msvc") 414 | else() 415 | set(RUST_COMPILER_TARGET "i686-pc-windows-msvc") 416 | endif() 417 | elseif(CMAKE_SYSTEM_NAME STREQUAL Darwin AND "${CMAKE_OSX_ARCHITECTURES}" MATCHES "^(arm64;x86_64|x86_64;arm64)$") 418 | # Special case for Darwin because we may want to build universal binaries. 419 | set(RUST_COMPILER_TARGET "universal-apple-darwin") 420 | else() 421 | # Determine default LLVM target triple. 422 | execute_process(COMMAND ${rustc_EXECUTABLE} -vV 423 | OUTPUT_VARIABLE RUSTC_VV_OUT ERROR_QUIET) 424 | string(REGEX REPLACE "^.*host: ([a-zA-Z0-9_\\-]+).*" "\\1" DEFAULT_RUST_COMPILER_TARGET1 "${RUSTC_VV_OUT}") 425 | string(STRIP ${DEFAULT_RUST_COMPILER_TARGET1} DEFAULT_RUST_COMPILER_TARGET) 426 | 427 | set(RUST_COMPILER_TARGET "${DEFAULT_RUST_COMPILER_TARGET}") 428 | endif() 429 | endif() 430 | 431 | set(CARGO_ARGS "build") 432 | 433 | if(NOT "${RUST_COMPILER_TARGET}" MATCHES "^universal-apple-darwin$") 434 | # Don't specify the target for macOS universal builds, we'll do that manually for each build. 435 | list(APPEND CARGO_ARGS "--target" ${RUST_COMPILER_TARGET}) 436 | endif() 437 | 438 | set(RUSTFLAGS "") 439 | 440 | if(NOT CMAKE_BUILD_TYPE) 441 | set(CARGO_BUILD_TYPE "debug") 442 | elseif(${CMAKE_BUILD_TYPE} STREQUAL "Release" OR ${CMAKE_BUILD_TYPE} STREQUAL "MinSizeRel") 443 | set(CARGO_BUILD_TYPE "release") 444 | list(APPEND CARGO_ARGS "--release") 445 | elseif(${CMAKE_BUILD_TYPE} STREQUAL "RelWithDebInfo") 446 | set(CARGO_BUILD_TYPE "release") 447 | list(APPEND CARGO_ARGS "--release") 448 | set(RUSTFLAGS "-g") 449 | else() 450 | set(CARGO_BUILD_TYPE "debug") 451 | endif() 452 | 453 | find_package_handle_standard_args(Rust 454 | REQUIRED_VARS cargo_EXECUTABLE 455 | VERSION_VAR cargo_VERSION 456 | ) 457 | --------------------------------------------------------------------------------