Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function in same package undefined

Tags:

go

My project structure is like this.

packagetest/
    main.go
    lib.go

In main.go, I have this code.

package main

import "fmt"

func main() {
    fmt.Println("Hello from main.go.")
    Test()
}

While in lib.go, I have this code.

package main

import "fmt"

func Test() {
    fmt.Println("This is the Test function in lib.go.")
}

When I try to compile with go build main.go, I get ./main.go:7: undefined: Test. Is this way of structuring my code possible?

like image 508
425nesp Avatar asked Aug 06 '14 22:08

425nesp


3 Answers

Try running just go build. When you give it a go file as an argument, it will not look for other go files. You can also do go build *.go

like image 109
Stephen Weinberg Avatar answered Nov 15 '22 12:11

Stephen Weinberg


This is an old post but it didn't answer my issue clearly, so I'm posting for the benefit of others in the future.

When run go run --help you will find this manual:

Run compiles and runs the main package comprising the named Go source files. A Go source file is defined to be a file ending in a literal ".go" suffix.

By default, 'go run' runs the compiled binary directly: 'a.out arguments...'.

go run <filename.go> is used for small programs with just a few files. With several files you will run into an issue where your main.go cannot find other files because go run doesn't compile and link them implicitly unless named. That's why go build the project works.

Alternatively, go run *.go (building all files) should work most of the time.

like image 36
Pandemonium Avatar answered Nov 15 '22 11:11

Pandemonium


On the golang.org webpage you can read about the build command that:

If the arguments are a list of .go files, build treats them as a list of source files specifying a single package.

So, go build main.go will treat main.go as a single package. Instead, you should use:

go build

to include all files in the folder.

like image 8
ANisus Avatar answered Nov 15 '22 11:11

ANisus