cargo 맛보기
개발 환경
이 문서에서 진행한 필자의 개발 환경은 다음과 같다.
- desktop: macbook pro 13 2020
- cpu: Intel Core i7 4core
- memory: 32GB
- rustup v1.24.3
- cargo vv1.58.0
이 문서는 여러분이 cargo
가 설치되어 있다고 가정한다. 만약 cargo
를 설치하지 않았다면, 이 문서를 참고하여 설치 및 설정을 진행하길 바란다.
또한 이 문서에서 진행하는 각 명령어는 MacOS, Linux 등의 OS는 잘 동작하겠지만 Windows는 동작하지 않을 수도 있다. 그 때는 "참고"절의 문서들을 참고하라.
cargo란
cargo
는 rust
의 빌드 시스템 및 패키지 매니저이다. 대부분의 프로젝트는 이 도구를 통해서 관리된다. 왜냐하면 여러분이 작성한 코드를 빌드하고 의존하고 있는 라이브러리를 다운로드 및 빌드를 손쉽게 해주기 때문이다.
java
프로그래밍 경험이 있다면, gradle
혹은 maven
, python
경험이 있다면 pipenv
, javascript
경험이 있다면 npm
, yarn
같은 도구들이라고 생각하면 된다.
cargo 맛보기
이제 cargo
로 rust
프로젝트를 생성한다. 터미널에 다음을 입력한다.
$ cargo new hello_cargo --bin
이러면, hello_cargo
라는 디렉토리가 생긴다. 해당 디렉토리로 이동하면, 다음 구조를 볼 수 있다.
# 디렉토리 이동
$ cd hello_cargo
# 디렉토리 구조 확인
$ tree
.
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
여기서 Cargo.toml
이란 파일을 확인해보자.
hello_cargo/Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
프로젝트 이름과 버전, 그리고 만든 개발자 등의 프로젝트의 메타 정보는 package
라는 부분에 작성된다. 또한 의존성 라이브러리가 있다면 dependencies
부분에 작성된다. 외부 라이브러리를 가져서와서 사용하는 방법은 추후 다른 문서에서 다루도록 하겠다. 지금은 이 파일에는 프로젝트의 메타 정보와 필요 라이브러리들이 작성된다고 생각하고 넘어가자.
이제 src/main.rs
를 살펴보자.
hello_cargo/src/main.rs
fn main() {
println!("Hello, world!");
}
우리가 작성하지 않았지만 main
함수가 작성되어 있다. 이제 프로젝트를 빌드해보자. 다음 명령어를 입력한다.
# 현재 위치 확인
$ pwd
/Users/gurumee/Workspace/hello_cargo
# 프로젝트 디버그용으로 빌드
$ cargo build
Compiling hello_cargo v0.1.0 (/Users/gurumee/Workspace/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 1.83s
이렇게 하면 target
디렉토리가 생성되었을 것이다. 다음 명령어로 빌드된 파일을 실행할 수 있다.
$ pwd
/Users/gurumee/Workspace/hello_cargo
# 디버그용 실행 파일 실행
$ ./target/debug/hello_cargo
Hello, world!
cargo build
명령어를 통해서 빌드된 실행 파일은 target/debug/
에 위치한다. 근데 이는 디버그 실행 파일이다. 개발자가 디버깅할 수 있는 정보들이 들어있다. 실제 배포되는 프로그램은 이러한 정보들을 노출하면 된다. 그러면 어떻게 실제 배포되는 실행 파일을 만들 수 있을까?
다음 명령어를 입력하면 배포용 실행 파일을 생성할 수 있다.
$ pwd
/Users/gurumee/Workspace/hello_cargo
# 프로젝트 배포용으로 빌드
$ cargo build --release
Compiling hello_cargo v0.1.0 (/Users/gurumee/Workspace/hello_cargo)
Finished release [optimized] target(s) in 0.26s
이 경우엔, target/release
라는 디렉토리가 생성된다. 배포용 실행 파일은 다음과 같이 실행시킬 수 있다.
$ pwd
/Users/gurumee/Workspace/hello_cargo
$ ./target/release/hello_cargo
Hello, world!
빌드 및 실행을 한 번에 다하고 싶다면 cargo run
명령어를 입력하면 된다.
# 디버그용으로 빌드 및 실행
$ cargo run
Compiling hello_cargo v0.1.0 (/Users/gurumee/Workspace/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.92s
Running `target/debug/hello_cargo`
Hello, world!
# 배포용으로 빌드 및 실행
$ cargo run --release
Compiling hello_cargo v0.1.0 (/Users/gurumee/Workspace/hello_cargo)
Finished release [optimized] target(s) in 0.23s
Running `target/release/hello_cargo`
Hello, world!
코드 변경이 있을 때 컴파일 및 빌드를 하는 것은 프로젝트가 커지면 커질수록 속도가 떨어진다. 만약 빠르게 컴파일 되는지 여부만 확인하고 싶다면 어떡해야 할까? 이 때는 cargo check
이라는 명령어를 이용할 수 있다. 먼저 main.rs
를 다음과 같이 변경한다.
hello_cargo/src/main.rs
fn main() {
println!("Hello, cargo!");
}
이제 cargo check
명령어를 입력해보자.
$ pwd
/Users/gurumee/Workspace/hello_cargo
# 컴파일 체크
$ cargo check
Checking hello_cargo v0.1.0 (/Users/gurumee/Workspace/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.14s
빌드와 실행 과정이 생략되기 때문에 위에서 진행했던 명령어들보다 훨씬 빠르다는 것을 알 수 있다. 이제 바뀐 코드가 잘 동작하는지 실행해서 확인해보자.
$ pwd
/Users/gurumee/Workspace/hello_cargo
$ cargo run
Compiling hello_cargo v0.1.0 (/Users/gurumee/Workspace/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.27s
Running `target/debug/hello_cargo`
Hello, cargo!
그 외, 테스트 코드를 실행할 수 있는 cargo test
, 벤치마크를 할 수 있는 cargo bench
의존성을 정리할 수 있는 cargo clean
등의 여러 명령어들이 있다. 이는 공식 문서와 cargo --help
를 통해서 확인할 수 있다.
$ cargo --help
Rust's package manager
USAGE:
cargo [+toolchain] [OPTIONS] [SUBCOMMAND]
OPTIONS:
-V, --version Print version info and exit
--list List installed commands
--explain <CODE> Run `rustc --explain CODE`
-v, --verbose Use verbose output (-vv very verbose/build.rs output)
-q, --quiet Do not print cargo log messages
--color <WHEN> Coloring: auto, always, never
--frozen Require Cargo.lock and cache are up to date
--locked Require Cargo.lock is up to date
--offline Run without accessing the network
--config <KEY=VALUE>... Override a configuration value (unstable)
-Z <FLAG>... Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
-h, --help Prints help information
Some common cargo commands are (see all commands with --list):
build, b Compile the current package
check, c Analyze the current package and report errors, but don't build object files
clean Remove the target directory
doc, d Build this package's and its dependencies' documentation
new Create a new cargo package
init Create a new cargo package in an existing directory
run, r Run a binary or example of the local package
test, t Run the tests
bench Run the benchmarks
update Update dependencies listed in Cargo.lock
search Search registry for crates
publish Package and upload this package to the registry
install Install a Rust binary. Default location is $HOME/.cargo/bin
uninstall Uninstall a Rust binary
See 'cargo help <command>' for more information on a specific command.