"undefined" function declared in another file?
Asked Answered
S

14

253

I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:

undefined: NewEmployee

Here is the source code:

main.go:

package main

func main() {
emp := NewEmployee()    
}

employee.go:

package main

type Employee struct {
    name string
    age int
}   

func NewEmployee() *Employee {
    p := &Employee{}
    return p
}

func PrintEmployee (p *Employee)  {
    return "Hello world!"
}
Story answered 26/1, 2015 at 15:27 Comment(10)
do your files have package statements? What you typed doesn't have a package x, also your main package typically only contains a single file, then imports the other pieces it needsArbitress
are you using go run? (and see golang.org/doc/code.html)Bosworth
@Crisfole yes the imports in main.go are "flag" and "fmt". Employee.go has no imports and both files are under a package called "main"Story
@Bosworth I tried both go run and go build, to no availStory
@JuanM, my question was is that the complete source of main.go and employee.go? Because all go files are supposed to have a package statement, and I don't see any in yours. See: golang.org/doc/code.html#PackageNamesArbitress
The last func of employee.go is wrong (no function name, no return type declared). It is not the problem you ask for, but it shows that there are more problems. Could you post the complete code and the complete error when compiling?Emanative
then show us what your doing! GOPATH, actual code, and how you're invoking the go tool.Bosworth
%GOPATH% C:\gocode\src the files Employee.go and main.go are under C:\gocode\srcStory
Please add the commands you use to compile to your question.Anselma
if you have multiple files then either build with go build or go build a.go b.goGuberniya
B
292

Please read "How to Write Go Code".

Use go build or go install within the package directory, or supply an import path for the package. Do not use file arguments for build or install.

While you can use file arguments for go run, you should build a package instead, usually with go run ., though you should almost always use go install, or go build.

Bosworth answered 26/1, 2015 at 15:46 Comment(4)
thanks for the input @JimB! I edited the environment variables (I also had forgotten to set GOBIN), moved my files to the correct location, but still when i try go intstall i get the same error. Any suggestions?Story
Are you certain there's no other errors? Your employee.go file can't compile as is. Otherwise, I need to see exactly what you're doing. Exact paths, invocation, etc.Bosworth
Also running go run . - the period being "this directory"Totally
@Puran go run *.go is a bad idea, because it will break if you have any build constraints or test files.Within
B
134

I just had the same problem in GoLand (which is Intellij IDEA for Go) and worked out a solution. You need to change the Run kind from File to Package or Directory. You can choose this from a drop-down if you go into Run/Edit Configurations.

Eg: for package ~/go/src/a_package, use a Package path of a_package and a Directory of ~/go/src/a_package and Run kind of Package or Directory.

Blanche answered 5/7, 2017 at 6:1 Comment(4)
Thank you, this is what I was looking for. Please mention that your answer is about Intellij IDEA.Febrifugal
I wish this would show up closer to the top by default. This is a really valuable answer.Heraldic
This addresses my problem with IDEA.Tramel
Just to clarify, go to the menu and choose Run -> Run... -> Edit Configuration... and you will see the Run kind. For me the Directory solved the issue. The Package gave me other errors, thanks.Duration
U
55

If you're using go run, do go run *.go. It will automatically find all go files in the current working directory, compile and then run your main function.

Untutored answered 29/5, 2018 at 21:31 Comment(2)
Are there any downfalls to doing it this way? This seems like the simplest answer to the OPs question.Ingrown
A more general solution under Bash: go run !(*_test).go -- Golang: run all .go files within current directory through the command line (multi file package)Subprincipal
A
21

go run . will run all of your files. The entry point is the function main() which has to be unique to the main package.

Another option is to build the binary with go build and run it.

Amaris answered 4/2, 2020 at 5:21 Comment(1)
I've been a while to run my old go project and forget how to run. I finally found it with your answer. This should be an upvoted answer!Abduce
A
18

You can try one of the following:

Method 1:

  • Assume that your project name is MyProject
  • Go to your path, run go build
  • It will create an executable file as your project name ("MyProject")
  • Then run the executable using ./MyProject

You can do both steps at once by typing go build && ./MyProject. Go files of the package main are compiled to an executable.

Method 2:

  • Just run go run *.go. It won't create any executable but it runs.
Ankus answered 2/12, 2018 at 13:34 Comment(0)
D
5

If you want to call a function from another go file and you are using Goland, then find the option 'Edit configuration' from the Run menu and change the run kind from File to Directory. It clears all the errors and allows you to call functions from other go files.

Dysphagia answered 1/6, 2018 at 3:25 Comment(0)
B
4

you should use go modules now, if you are not following How to write go code

With go module you don't have to put the code in the $GOPATH/src. it can live in any other location as well.

You can move the code to different directory like /employee, To make it work Just under employee directory initialise the go module

go mod init example.com/employee
Blackberry answered 10/7, 2020 at 7:37 Comment(0)
U
3

I had a nasty import "C" in one of my go files.

Uncrown answered 20/8, 2022 at 23:9 Comment(0)
D
2

I also encountered this problem when using goland.
Need to run as a package enter image description here

The following two ways can be solved.

1

enter image description here

2

enter image description here

Dislodge answered 28/7, 2023 at 3:19 Comment(0)
O
1

I ran into the same issue with Go11, just wanted to share how I did solve it for helping others just in case they run into the same issue.

I had my Go project outside $GOPATH, so I had to turned on GO111MODULE=on without this option turned on, it will give you this issue; even if you you try to build or test the whole package or directory it won't be solved without GO111MODULE=on

Offspring answered 14/5, 2019 at 6:46 Comment(0)
L
1

While this doesn't directly address the OP's specific issue, I thought I'd chime in with the solution to my "undefined" error: the file with the undefined method had a build constraint (build tag).

More specifically, I accidentally included a build constraint to remove testing files from my deployed application binary in a utility function file used by my deployed binary. So in the OP's example - if employee.go had a build constraints their go build command would need to include a -tags flag matching the constraint in in order to have the file included.

For more info read this blog post: https://dave.cheney.net/tag/build-constraints

Ladawnladd answered 25/5, 2021 at 5:56 Comment(0)
N
1

Took a while to drill down my own MRE for this, so hopefully it will help others, despite being brief:

This can also occur if your functions / structs are defined in a file that has import "C", which will be silently ignored if CGO_ENABLED=0 is in your go environment, leading to you staring at a two file package that somehow is unable to share between themselves.

Niece answered 26/6, 2021 at 1:48 Comment(0)
V
1

In GoLand,

  • right click a directory
  • GoLand will give you the option for build it and run it
  • it will also create a run configuration draft for you
  • you can save with an option of the upper right dropdown

If you right clic a file, it shows you commands to run, debug, test that file.

If you right clic a directory, it will be the same for that "package", expecting a main.go file inside the directory

Vespers answered 21/11, 2021 at 7:23 Comment(1)
I'm getting this error in my github actions using goreleaser.Morlee
G
-2

If your source folder is structured /go/src/blog (assuming the name of your source folder is blog).

  1. cd /go/src/blog ... (cd inside the folder that has your package)
  2. go install
  3. blog

That should run all of your files at the same time, instead of you having to list the files manually or "bashing" a method on the command line.

Gwendolyn answered 30/11, 2017 at 20:22 Comment(1)
And here's a digital ocean article too: digitalocean.com/community/tutorials/…Gwendolyn

© 2022 - 2025 — McMap. All rights reserved.