Skip to content

Instantly share code, notes, and snippets.

@thoughtpolice
Created January 11, 2019 00:34
Show Gist options
  • Save thoughtpolice/30f45c0a2d46571d979a0a5447f9ce5c to your computer and use it in GitHub Desktop.
Save thoughtpolice/30f45c0a2d46571d979a0a5447f9ce5c to your computer and use it in GitHub Desktop.
Static C++17 binaries with Clang, Musl, and libc++, using Nix
{ useMusl ? false
}:
let
nixpkgs = import (builtins.fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/004cb5a694e39bd91b27b0adddc127daf2cb76cb.tar.gz";
sha256 = "0v5pfrisz0xspd3h54vx005fijmhrxwh0la7zmdk97hqm01x3mz4";
}) {};
pkgs = if useMusl then nixpkgs.pkgsMusl else nixpkgs;
src = pkgs.writeText "test.cc" ''
#include <cstdlib>
#include <iostream>
#include <tuple>
using namespace std;
std::tuple<char, int, bool>
example_tuple()
{
char a = 'a';
int i = 123;
bool b = true;
return std::make_tuple(a, i, b);
}
int main() {
auto [a, i, b] = example_tuple();
cout << a << endl;
cout << i << endl;
cout << b << endl;
return EXIT_SUCCESS;
}
'';
staticFlag = pkgs.lib.optionalString useMusl "-static";
ccapp = { stdenv }:
stdenv.mkDerivation rec {
name = "cc-test-${version}";
version = "0.0";
inherit src;
unpackPhase = ":";
configurePhase = ":";
buildPhase = ''
clang++ -Wall -std=gnu++17 -stdlib=libc++ -O2 -o test ${src} ${staticFlag}
strip test
'';
installPhase = ''
install -D -m555 test $out/bin/llvm-musl-test
'';
};
drv = pkgs.callPackage ccapp {
stdenv = pkgs.llvmPackages_7.stdenv;
};
in drv
@thoughtpolice
Copy link
Author

$ nix build -f llvm-static-musl.nix --arg useMusl true
$ ldd ./result/bin/llvm-musl-test
        not a dynamic executable
$ ./result/bin/llvm-musl-test
a
123
1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment