一、hello world经典入门:
每学一门语言都是从经典的hell world来开始,学习rust也不例外。这里我就不就演示rust在ubuntu18.04里面的环境搭建了,网上有很详细的教程。那么现在我在当前目录下创建一个test目录来专门放rust工程项目代码的:
root@txp:~/test# touch main.rs
root@txp:~/test# ls
main.rs
main.rs文件里面的内容(注意在rust里面编程的源文件后缀是".rs"):
fn main() {
println!("hello world");
}
然后进行编译:
root@txp:~/test# rustc main.rs
输出结果:
root@txp:~/test# ls
main main.rs
root@txp:~/test# ./main
hello world
分析:
代码里面同样和大多数编程语言一样都有一个main函数;注意这里的println!是一个rust宏,而println才是一个函数。
二、cargo工程管理工具:
1、cargo是rust的构建系统和包管理器,一般我们会用来管理工程项目(因为它可以为你处理很多任务,比如构建代码、下载依赖库并编译这些库。(我们把代码所需要的库叫做 依赖(dependencies))。和我们知道的cmake、makefile差不多。既然它可以来管理工程项目,那么现在我们就来实践一下,在之前的test目录返回,我重新使用cargo创建了一个工程目录:
root@txp:~# cargo new hello_wolrd
Created binary (application) `hello_wolrd` package
root@txp:~# cd hello_wolrd/
root@txp:~/hello_wolrd# ls
Cargo.toml src
root@txp:~/hello_wolrd# cd src
root@txp:~/hello_wolrd/src# ls
main.rs
你会看到在工程目录下自动创建了一个Cargo.toml文件和源码目录,它里面放着就是main.rs了,Cargo.toml文件内容(这个文件类型时cargo的配置文件的书写格式):
[package]
name = "hello_wolrd"
version = "0.1.0"
authors = ["root"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
注:
接下来的四行设置了 Cargo 编译程序所需的配置:项目的名称、版本、作者以及要使用的 Rust 版本。Cargo 从环境中获取你的名字和 email 信息,所以如果这些信息不正确,请修改并保存此文件。
最后一行,[dependencies],是罗列项目依赖的片段的开始。在 Rust 中,代码包被称为 crates。这个项目并不需要其他的 crate。
现在我们来看src目录下的main.rs内容:
fn main() {
println!("Hello, world!");
}
你可以看到这个和我们之前写的hello_world程序一样。
2、使用cargo来构建项目管理:
(1)使用命令cargo build来构建项目:
root@txp:~/hello_wolrd/src# cargo build
Compiling hello_wolrd v0.1.0 (/root/hello_wolrd)
Finished dev [unoptimized + debuginfo] target(s) in 17.04s
root@txp:~/hello_wolrd/src# ls
main.rs
先来运行它:
root@txp:~/hello_wolrd/src# cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.39s
Running `/root/hello_wolrd/target/debug/hello_wolrd`
Hello, world!
(2)cargo check命令是用来快速查看代码并确保它可以进行编译,但是最终不产生可执行文件:
root@txp:~/hello_wolrd/src# cargo check
Checking hello_wolrd v0.1.0 (/root/hello_wolrd)
Finished dev [unoptimized + debuginfo] target(s) in 3.66s
为什么你会不需要可执行文件呢?通常 cargo check 要比 cargo build 快得多,因为它省略了生成可执行文件的步骤。
三、小结:
本次分享主要是简单的分享如果去构建rust项目以及如何去编译和运行rust代码,下期我们将正式进入rust入坑大门学习之旅!更多内容可以关注公众号:TXP嵌入式
本文使用 mdnice 排版