main() cannot call method in another file

1,061 views
Skip to first unread message

Cam

unread,
Oct 23, 2019, 1:20:26 AM10/23/19
to golang-nuts
Hi everyone on Golang group,

I'm having difficulty with some simple code, and appreciate if someone can point out a solution.

There is a simple main package that looks like this:

                                                            hello.go
                                                            main.go

hello.go:

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

main.go

package main
func main() {
  SayHello()
}

Trying to run main.go is producing an error:

# command-line-arguments
go/src/github.com/username/playground/main.go:4:2: undefined: SayHello

Why is this error happening? Is my packaging done wrong?

Tamás Gulácsi

unread,
Oct 23, 2019, 2:25:38 AM10/23/19
to golang-nuts
"go run" builds and runs what you tell it: only main.go.
If you have a package with more files, use "go build && playground".

Guy Allard

unread,
Oct 24, 2019, 8:17:54 AM10/24/19
to golang-nuts
Use:

go run *.go

or

go build *.go

Chris Hines

unread,
Oct 24, 2019, 10:29:01 AM10/24/19
to golang-nuts
go run <dir> works now too and pulls in all the files in the package at <dir> so "go run ." is a nice shortcut that works more like the other subcommands of the go tool.

Cam

unread,
Oct 24, 2019, 1:14:37 PM10/24/19
to golang-nuts
Your suggestions helped me build the files with the same project structure:

// From folder username/

go build playground/*.go

// From folder playground/

go build *.go

go build .


Thanks !!
Reply all
Reply to author
Forward
0 new messages