我有2个go文件:

/Users/username/go/src/Test/src/main/Test.go

1
2
3
4
5
6
7
package main

import"fmt"

func main() {
    fmt.Printf(SomeVar)
}

和文件/Users/username/go/src/Test/src/main/someFile.go

1
2
3
package main

const SomeVar ="someFile"

但是我不断得到编译器错误:

/Users/username/go/src/Test/src/main/Test.go:6: undefined: SomeVar

有人可以向我解释为什么SomeVar被标记为未定义吗?

  • 您如何调用编译器? 如果您运行go build Test.go,则它将仅将该文件视为软件包的一部分。
  • 1.使用go build-go run实际上仅适用于简单的单个文件程序。 2.不要将文件夹命名为main。
  • 请显示您的$GOPATH
  • 在另一个文件中声明的golang"未定义"函数的可能重复项?

尝试

1
go run Test.go someFile.go

引用:

I think you're misunderstanding how the go tool works. You can do"go
build" in a directory, and it'll build the whole package (a package is
defined as all .go files in a directory). Same for go install, go
test, etc. Go run is the only one that requires you to specify
specific files... it's really only meant to be used on very small
programs, which generally only need a single file.

这样:

1
go build && ./program_name

也可以看看

  • @staticx:它提供了错误的说明和解决方案。 它为问题提供了答案。
  • 现在可以了。 您的帖子出现在低质量队列中。
  • 这对我有帮助! 我在尝试在Gogland中运行大型程序时遇到了这个问题。 我通过运行配置并将项目类型切换到目录来修复它!

您的代码是正确的:

  • someFile.goTest.go属于同一个程序包(main)
  • SomeVar是在顶层声明的const,因此具有包块作用域,即main包块作用域
  • 因此,SomeVar是可见的,并且可以在两个文件中进行访问

(如果您需要在Go中查看作用域,请参考语言规范-声明和范围)。

那么为什么会出现undefined错误?

如果从/Users/username/go/src/Test/src/main启动,您可能启动了go build Test.gogo run Test.go,它们都产生以下输出:

1
2
# command-line-arguments
./Test.go:6: undefined: SomeVar

您可以在这里找到原因:命令执行

如果使用.go文件列表启动go buildgo run,它将把它们视为指定单个程序包的源文件列表,即,它认为main程序包中没有其他代码,因此是错误。
解决方案包括所有必需的.go文件:

1
2
3
go build Test.go someFile.go

go run Test.go someFile.go

go build也将不带任何参数,从而构建它在包中找到的所有文件:

1
go build

注意1:上面的命令引用本地软件包,因此必须从/Users/username/go/src/Test/src/main目录启动

注意2:尽管其他答案已经提出了有效的解决方案,但我还是决定在此处添加一些详细信息来帮助社区,因为这是开始使用Go时的常见问题:)