Go cli
Introduction
This is just a page on go command options
go help <command>
// e.g.
go help test
We can go to https://golang.org/cmd/go/ for online
Building and Running
Environment
For me I have set up my PATH to include go and my GOROOT to be the parent directory of the src folder.
export PATH=/usr/local/go/bin:$PATH
cd blah1/blah2/src/..
export GOPATH=`pwd`
Run
Compiles and run a program without leaving artefacts.
go run src/cmds/hello/hello.go
Build
Compiles but does not run a program. Given the tree
This command will build the library but not produce anything.
go build hello
This command will build the binary and produce a binary
go build cmds/hello
Adding the -i forces the intermediate files to be created on disk in the pkg directory
go build -i cmds/hello
Install
Go install will do all of what build will do but will also create the bin and the library in the workspace. e.g.
go install cmds/hello
Other Commands
So here are some other flags
-a force rebuild -n dry run with verbose -n no dry run with verbose -p for processors -v verbose
Race Flag
This is a flag to detect issues with concurrency adding this to the run can help find issues. Just run the code with -race. Without the shadowing to local scope this code would fail.
package main
import "fmt"
import "sync"
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
// ===>>> i := i
go func() {
fmt.Println(i)
wg.Done()
}()
}
wg.Wait()
}
Running with -race will help
==================
WARNING: DATA RACE
Read at 0x00c0000160b0 by goroutine 7:
main.main.func1()
/home/iwiseman/dev/courses/go-cli/03/demos/demos/03-race/main.go:12 +0x3c
Previous write at 0x00c0000160b0 by main goroutine:
main.main()
/home/iwiseman/dev/courses/go-cli/03/demos/demos/03-race/main.go:8 +0x108
Goroutine 7 (running) created at:
main.main()
/home/iwiseman/dev/courses/go-cli/03/demos/demos/03-race/main.go:11 +0xe4
==================
This did not impress. We have to build the standard library doing
sudo /usr/local/go/bin/go build -buildmode=shared std
Just do not like the sudo, guess in a container not a problem. Anyway we just need to build the program
go build -linkshared cmds/hello
C/C++ Integration
Static Linking
We can link go archives to C by
- Include "C" package
- Creating an empty main (no idea why)
- Add comment with export name - note no space
package main
import "fmt"
import "C"
func main() {}
//export Hello
func Hello() {
fmt.Println("Hello")
}
Next issue the build mode command which will produce an include hello.h
go build -buildmode=c-archive hello.go
From there we are good to go - no pun intended
cc test.c ./hello.a -;pthread
Dynamic Linking
No surprises except of course the crappyness to the approach with export comments. I really think they are just trying to keep the precious keyword count down
go build -buildmode=c-shared hello.go