Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a go app is buildable?

Tags:

compilation

go

I write some code then build the app to an output file, but sometimes I just want to check if the app is buildable, i.e. has no errors and produces a compiled output, but without actually writing the output file.

I tried this variant and it seemed to work:

go build -o /dev/null myapp

But I suspect there must be a more "official" Go way to check if it can build.

Please advise!

like image 284
Sergei Basharov Avatar asked Aug 31 '25 06:08

Sergei Basharov


1 Answers

To check if a package or app is buildable, go build is the "official" way.

What you did is the easiest way. In my opinion, you should stick to it. Alternatively you may do:

go build -o delme && rm delme

But it's somewhat slower as it has to write the result which is then deleted, but this solution is platform independent (as /dev/null does not exist on windows).

When building a command (main package), by definition go build will create and leave the result in the current working directory. If you build a "normal" package (non-main), the results will be discarded. See details here: What does go build build?

So if it bothers you that you have to use the -o /dev/null param or manually delete the result, you may "transform" your main package to a non-main, let's call it main2. And add a new main package which should do nothing else but import and call main2.Main(). Building the main2 package will not leave any files behind.

E.g. myapp/main.go:

package main

import "myapp/main2"

func main() { main2.Main() }

myapp/main2/main2.go:

// Every content you originally had in main.go

package main2

func Main() {
    // ...
}
like image 77
icza Avatar answered Sep 02 '25 19:09

icza