Go: Difference between revisions

From NixOS Wiki
imported>Makefu
initial batch of nixos-users
 
imported>Fadenb
m Syntax highlighting
Line 3: Line 3:
== Compile go program with static compile flags ==
== Compile go program with static compile flags ==


If <code>go build -ldflags &quot;-s -w -linkmode external -extldflags -static&quot;</code> fails on NixOS, with the error message <code>cannot find</code>-lpthread<code>and</code>cannot find -lc` - it is because the linker cannot find static glibc to link with. You need to have glibc.static in your environment (and have CFLAGS/LDFLAGS adjusted accordingly).
If <syntaxhighlight lang="bash" inline>go build -ldflags "-s -w -linkmode external -extldflags -static"</syntaxhighlight> fails on NixOS, with the error message <code>cannot find</code>-lpthread<code>and</code>cannot find -lc` - it is because the linker cannot find static glibc to link with. You need to have glibc.static in your environment (and have CFLAGS/LDFLAGS adjusted accordingly).


One way to achieve this is to have something like the following as <code>shell.nix</code> and run the compilation in a nix-shell:
One way to achieve this is to have something like the following as <code>shell.nix</code> and run the compilation in a nix-shell:


<pre class="nix">with import &lt;nixpkgs&gt; {}; {
<syntaxhighlight lang="nix">with import <nixpkgs> {}; {
   devEnv = stdenv.mkDerivation {
   devEnv = stdenv.mkDerivation {
     name = &quot;dev&quot;;
     name = "dev";
     buildInputs = [ stdenv git go glibc.static ];
     buildInputs = [ stdenv git go glibc.static ];
     CFLAGS=&quot;-I${pkgs.glibc.dev}/include&quot;;
     CFLAGS="-I${pkgs.glibc.dev}/include";
     LDFLAGS=&quot;-L${pkgs.glibc}/lib&quot;;
     LDFLAGS="-L${pkgs.glibc}/lib";
   };
   };
}</pre>
}</syntaxhighlight>

Revision as of 16:00, 27 August 2017

Go is a statically-typed language with syntax loosely derived from that of C, adding garbage collected memory management, type safety, some dynamic-typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library.

Compile go program with static compile flags

If go build -ldflags "-s -w -linkmode external -extldflags -static" fails on NixOS, with the error message cannot find-lpthreadandcannot find -lc` - it is because the linker cannot find static glibc to link with. You need to have glibc.static in your environment (and have CFLAGS/LDFLAGS adjusted accordingly).

One way to achieve this is to have something like the following as shell.nix and run the compilation in a nix-shell:

with import <nixpkgs> {}; {
  devEnv = stdenv.mkDerivation {
    name = "dev";
    buildInputs = [ stdenv git go glibc.static ];
    CFLAGS="-I${pkgs.glibc.dev}/include";
    LDFLAGS="-L${pkgs.glibc}/lib";
  };
}