-1

I have a simple question on the build process in Go.

I have a very simple app, the simplest possible, which is structured like this

- myapp
  - main
    - main.go
  - go.mod

with main.go being

package main
import "fmt"
func main() {
    fmt.Println("Hello !")
}

From within the folder myapp I run the command go build -o bin/main main/main.go and everything works.

No I decide to create a new function doStuff() in the package main to be called by main() but I want to have it in a different file stuff.go. So the new structure of the app is

- myapp
  - main
    - main.go
    - stuff.go
  - go.mod

with main.go being

package main
import "fmt"
func main() {
    fmt.Println("Hello !")
    doStuff()
}

and stuff.go being

package main
import "fmt"
func doStuff() {
    fmt.Println("I am doing stuff")
}

If I try now to run the same build command go build -o bin/main main/main.go I get an error main/main.go:4:2: undefined: doStuff.

But if I move into the main folder and run from there the command go build -o ../bin/main everything works.

Which is the reason of this behaviour? Shall I always run the go build command from the folder where main() is if i want to create an executable?

Picci
  • 16,775
  • 13
  • 70
  • 113
  • 6
    Go's compilation unit is a package, not a file, so it is rarely correct to specify filenames on the command line. Run `go build -o bin/main ./main`. – Peter Jul 16 '20 at 08:08
  • Thanks. I was brought to specify the file name by the fact that the template provided by the serverless framework for lambda functions in Go actually uses the file name in the build command. Now it is clear. – Picci Jul 16 '20 at 08:21

1 Answers1

-1

If package main is split into multiple files, you can do either of the following:

go build -o bin/main ./main

or

go build -o bin/main ./main/*

Main packages are typically very small. All business logic tends to either be in pkg/ or internal/.

Serge
  • 634
  • 4
  • 9
  • The last one is plain wrong: Think about *_test.go or *_windows.go files. – Volker Jul 16 '20 at 11:12
  • I stated you can do it. Works as per the question is asked. You should not have unit tests for your main pkg, as mentioned in my answer, business logic is elsewhere. Thanks – Serge Jul 16 '20 at 22:54
  • Furthermore, the command works perfectly fine with *_test.go in /main dir. Sorry but you are incorrect there. – Serge Jul 16 '20 at 23:03