想嘗試使用 Nix 不一定要使用 NixOS,可以安裝 Nix 到 Linux 或 Mac 作業系統,就能使用 nix-env 和 nix-shell。
Single User Installation 會使 Nix Store 被執行 install 的使用者擁有,因此全系統只有該使用者可以用 Nix。(Nix 首頁沒提到 Multi User Installation,它藏在 Mamual 裡) (因為 Multi User Installation 比較難移除?)
簡報。
大部分內容來自 The Purely Functional Software Deployment Model 論文 Part I (重點整理)。
有沒有人剛剛在安裝 Nix 時遇到問題的?
Nix Pills, Chapter 3. Enter the Environment。
開 nix repl 玩一下 Nix 語言。
-
,因為很多套件名稱裡面都有 -
。但語言慣例還是用 camelCase。// hello.c
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("Hello, Nix World!\n");
return 0;
}
let
pkgs = import <nixpkgs> { };
in
derivation {
name = "hello";
system = "x86_64-linux";
builder = "${pkgs.bash}/bin/bash";
args = [
"-c"
''
export PATH="${pkgs.coreutils}/bin:${pkgs.gcc}/bin"
mkdir $out
gcc "${./hello.c}" -o "$out/hello"
''
];
}
nixpkgs.stdenv.mkDerivation
。<nixpkgs>
是 Nix 官方維護的 components 定義集,就像 Nix 的標準函式庫。pkgs.bash
是個變數,轉成 string 會變成 build 的輸出路徑 (out path),所以我們可以寫 "${pkgs.bash}/bin/bash"
。nix-repl> pkgs = import <nixpkgs> { }
nix-repl> "${pkgs.bash}"
"/nix/store/b9p787yqaqi313l9rr0491igjwyzqfmw-bash-4.4-p23"
"/nix/store/b9p787yqaqi313l9rr0491igjwyzqfmw-bash-4.4-p23
不一定會真的存在,只是我們知道如果有被 build 好,就會在這個路徑下。寫過 Makefile 嗎?
// hello.c
#include <stdio.h>
#include "message.h"
int main(int argc, char const *argv[])
{
printf("%s", message);
return 0;
}
// message.h
extern const char message[];
// message.c
const char message[] = "Hello, Nix World!\n";
Makefile:
all: hello
hello: hello.c message.o
gcc -I./ hello.c message.o -o hello
message.o: message.c message.h
gcc -c message.c -o message.o
可以用 Nix 改寫:
let
pkgs = import <nixpkgs> {};
message = derivation {
name = "message";
system = builtins.currentSystem;
builder = "${pkgs.bash}/bin/bash";
args = [
"-c"
''
export PATH="${pkgs.coreutils}/bin:${pkgs.gcc}/bin"
mkdir $out
cp ${./message.h} $out/message.h
gcc -c ${./message.c} -o $out/message.o
''
];
};
hello = derivation {
name = "hello";
system = builtins.currentSystem;
builder = "${pkgs.bash}/bin/bash";
args = [
"-c"
''
export PATH="${pkgs.coreutils}/bin:${pkgs.gcc}/bin"
mkdir $out
echo ${message}
gcc -I${message} ${./hello.c} ${message}/message.o -o $out/hello
''
];
};
in
hello
stdenv.mkDerivations
, etc.…
use nix
但有人寫了更快、有 cache、可以避免被 GC 的版本