How do I cross compile my own package (rather than something in nix-pkgs)

The cross compilation tutorials all have examples of how to use nix to cross compile packages in nixpkgs, but I cannot find one on how to cross compile my own package. I have the following default.nix.

{ pkgs ? import <nixpkgs> {} }:
   pkgs.stdenv.mkDerivation {
     name = "atest";
     src = ./src;

     buildInputs = [
       pkgs.SDL2
       pkgs.SDL2.dev
     ];

     buildPhase = ''
     gcc -o example main.c -lSDL2
     '';

     installPhase = ''
       mkdir -p $out
       cp example $out/
     '';
    }

and in src/main.c I have

#include <SDL2/SDL.h>

int main(int arc, char ** argv) {
    if (SDL_Init( SDL_INIT_VIDEO ) < 0) {
        printf("SDL could not initialize!\n");
    } else {
        SDL_CreateWindow(
            "SDL2 Demo",
            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
            800, 600,
            SDL_WINDOW_SHOWN
        );

        SDL_Delay(2000);
    }

    return 0;
}

If I type nix-build it builds without problem for linux, but I cannot figure out how to cross compile this for windows (mingw) with nix.

First you need to separate your nix file in two files, one that does callPackage on the other:
default.nix:

{ pkgs ? import <nixpkgs> {} }:
   pkgs.callPackage ./myapp.nix {}

and ./myapp.nix:

{ stdenv, SDL2 }: mkDerivation { ... }

Then check that it still builds. Then to cross compile, replace usage of pkgs.callPackage by pkgs.pkgsCross.mingw64.callPackage.

Good luck :slight_smile:

5 Likes

Thanks, that solves it!