Getting a header file to compile with nix

OKAY so for awhile I’ve been trying to get a header file I made in C and use it without typing in the full path, thing is: I don’t work understand how I would be able to compile the header file and then link it, since NixOS functions very differently than most operating systems. Bare in mind I’m a bit fresh when it comes to developing with nix, so please be patient with me. Here’s my nix file I tried to get working:

printn.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char printn(const char codes[]) {

  char *str = malloc(strlen(codes));

  for (int i = 0; i < strlen(codes); i++) {
    str[i] = codes[i];
  };

  puts(str);

  return *str;
}

So the objective here is to make it compile and then link it so I can use in my “main.c” however I don’t exactly know how to do that.

printn.nix:

with import <nixpkgs>{};

let
        name = "printn";
        version = "0.0.1";
in

stdenv.mkDerivation {
        pname = "${name}";
        version = "${version}";
        src = ./.;

        # gcc -c ${name}.c -o ${name}.o ; ar crs lib${name}.a ${name}.o

        buildPhase = ''
        gcc -c -fPIC ${name}.c -o ${name}.o
        gcc -shared -o lib${name}.so ${name}.o
        '';

        installPhase = ''
        mkdir -p $out/lib
        mkdir -p $out/include

        runHook preInstall
        cp ${name}.o $out/lib
        cp ${name}.h $out/include
        ln -sf $out/lib/${name}.so.${version} $out/lib/${name}.so.0
        runHook postInstall
        '';
}

Remember this is not a program, its a library that I want to use. But again I struggle to know how I would use it dynamically.

That looks right, the issue is probably how you use this package. Can you show us how you do that?

I’d also suggest using a makefile rather than manually defining the build steps. While you’re at it, consider using cmake, meson, or plain old traditional autotools.