Out of source builds (external build directory) with Cargo?

前端 未结 2 1875
暖寄归人
暖寄归人 2021-02-07 09:13

Having used CMake, I\'ve become used to out-of-source builds, which are encouraged with CMake. How can out-of-source builds be done with Cargo?


Using in-source-bui

2条回答
  •  -上瘾入骨i
    2021-02-07 09:29

    You can specify the directory of the target/ folder either via configuration file (key build.target-dir) or environment variable (CARGO_TARGET_DIR). Here is an example using a configuration file:

    Suppose you want to have a directory ~/work/ in which you want to save the Cargo project (~/work/foo/) and next to it the target directory (~/work/my-target/).

    $ cd ~/work
    $ cargo new --bin foo
    $ mkdir .cargo
    $ $EDITOR .cargo/config
    

    Then insert the following into the configuration file:

    [build]
    target-dir = "./my-target"
    

    If you then build in your normal Cargo project directory:

    $ cd foo
    $ cargo build
    

    You will notice that there is no target/ dir, but everything is in ~/work/my-target/.


    However, the Cargo.lock is still saved inside the Cargo project directory, but that kinda makes sense. For executables, you should check the Cargo.lock file into your git! For libraries, you shouldn't. I guess having to ignore one file is better than having to ignore an entire folder.

    Lastly, there are a few caveats to changing the target-dir, which are listed in the PR which introduced the feature.

提交回复
热议问题