3

This is newbie question... Let's say I have a Go code in a directory(repository initiated here as root) called "myprogram". And I write some packages divided in several sub-directories.

Then I have

repository, root directory

myprogram
----------- package1
----------- package2
----------- package3

Then in the myprogram directory, I will write the code with main package for main program and the main program will call all the packages that are defined in the sub-directories, like the following:

main.go

import "github.com/username/package1"
import "github.com/username/package2"
import "github.com/username/package3"

func main() {
    package1.Function1()
    ....
}

Then I can just run this code with

$ go run main.go

I have no problem so far. But what if this program has some features with flags?

$ go run main.go  flag1 flag2

This works, but I want to run something like

$ myprogram
$ flag1
....
$ flag2

Since all the programs and source code will be contained under the directory myprogram which is also the name of the project, repository

myprogram
----------- package1
----------- package2
----------- package3

We run Vim with the command, something like this...

$ vim

To summarize, how do I make my program run by command, not by go run main ?

Is there any open source repository that I can refer to? Or please let me know the package or documentation to read. I tried

go install

But can't make it work like I wanted.

Thanks a lot!

  • 1
    To expand on @FuZxxl's answer: `go run` should only ever be used for a quick, single-file check. Go isn't a scripting language, so you should be compiling it (go run effectively does that and discards the binary). When you have multiple files as part of the one package (either `package main` or `package mylibrary`) you'll need to use `go build`. – elithrar Feb 21 '14 at 03:52

2 Answers2

2

Use go build. This will create an executable of the package in the current directory. You can also run go build <packagename>, which creates a binary in $GOPATH/bin.

fuz
  • 88,405
  • 25
  • 200
  • 352
  • I was always confused by go build and go build packagename, so go build packagename, this is the one that creates the binary in GOPATH/bin right? not go build –  Feb 21 '14 at 03:31
0

Take a look at this one

  • it is an open source repository that people can refer to
  • it illustrates how to deal with the cases that the main program can have some sub features that need different flags
  • and for sure it shows how to make programs run by command, not by go run main
  • and most importantly, make the whole process as simple as possible by auto-generate all things that can be auto-generated
xpt
  • 20,363
  • 37
  • 127
  • 216