Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile Go program consisting of multiple files?

I have a small program that consists of three files, all belonging to the same package (main). But when I do go build main.go the build doesn't succeed. When it was just one file (main.go), everything worked fine.

Now that I took some effort to separate the code, it looks like the compiler is unable to find the stuff that was taken out of main.go and put into these two other files (that reside in the same directory as the main.go). Which results in undefined 'type' errors.

How to compile this program that consists of multiple files?

like image 282
Vitaly Avatar asked May 31 '12 17:05

Vitaly


People also ask

How do I run a go program with multiple files?

If you are trying to run multiple files on localhost using gorilla mux in go as per latest version(1.11). Try using any of the following 2 commands. go install && FolderName -port 8081 . go build && ./FolderName -port 8081.

Does go compile to an executable?

go build will compile a program into an executable file. To demonstrate, we will use a simple Hello World example main.go: package main import fmt func main() { fmt. Println("Hello, World!") }


1 Answers

New Way (Recommended):

Please take a look at this answer.

Old Way:

Supposing you're writing a program called myprog :

Put all your files in a directory like this

myproject/go/src/myprog/xxx.go 

Then add myproject/go to GOPATH

And run

go install myprog 

This way you'll be able to add other packages and programs in myproject/go/src if you want.

Reference : http://golang.org/doc/code.html

(this doc is always missed by newcomers, and often ill-understood at first. It should receive the greatest attention of the Go team IMO)

like image 133
Denys Séguret Avatar answered Sep 19 '22 09:09

Denys Séguret