How to compile and run a 'Hello World' C script using a Rust build file with the cc crate.
In a previous post here on Dev, I grumbled about being impatient while learning Rust. And, after floundering miserably at Rust procedural macros, I promised to go back to the Rust Playground and get more experience.
On my way back there, however, I stopped off long enough to look through some of The Cargo Book and found a simple way to compile and display a "Hello, World" C file by adding it to a Rust build script.
Check out the "Build a Native Library" section of The Cargo Book and look at its examples. I chose to focus on the Rust build script using a build-dependencies entry from Crates.io. cc-rs is "[a] library to compile C/C++/assembly into a Rust library/application."
In The Cargo Book, find the text that begins: "Not to fear, though, this is where a build-dependencies entry would help!"
Enter and save the simple code examples that are shown. And be sure to place each file in the correct subdirectory. For example, the build.rs file should not be placed into the src folder. Put it in the folder with the Cargo.toml file. Meanwhile, be sure the hello.c file is placed in the src folder, along with the main.rs file.
I chose to add two more "message" lines to the printf(); portion of the boring hello.c file. This C file is compiled and displays text on the screen right after you enter cargo build
at the prompt and then cargo run
. Here is my hello.c example:
// hello.c - Simple C program to display "Hello World"
// Header file for input output functions
#include <stdio.h>
// main function - where program execution begins
void hello(){
// prints hello world
printf("Hello, Rust World! This is a message from C World!\n");
printf("And another message to Rust World from C World!\n");
printf("But now, that's all, folks!\n");
}
C:\Users\sidun\Documents\Rust_code\projects\hello-world-from-c>cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target\debug\hello-world-from-c.exe`
Hello, Rust World! This is a message from C World!
And another message to Rust World from C World!
But now, that's all, folks!
After getting ahead of my Rust-beginner skills and floundering at procedural macros, it has been nice little confidence boost to see that I can get some Rust and C to work together. If you are a Rust beginner, be sure to spend some quality study time with The Cargo Book, as well as The Rust Programming Language book.
Top comments (0)