我有2个go文件:
1 2 3 4 5 6 7 | package main import"fmt" func main() { fmt.Printf(SomeVar) } |
和文件
1 2 3 | package main const SomeVar ="someFile" |
但是我不断得到编译器错误:
/Users/username/go/src/Test/src/main/Test.go:6: undefined: 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.go 和Test.go 属于同一个程序包(main ) -
SomeVar 是在顶层声明的const ,因此具有包块作用域,即main 包块作用域 -
因此,
SomeVar 是可见的,并且可以在两个文件中进行访问
(如果您需要在Go中查看作用域,请参考语言规范-声明和范围)。
那么为什么会出现
如果从
1 2 | # command-line-arguments ./Test.go:6: undefined: SomeVar |
您可以在这里找到原因:命令执行
如果使用
解决方案包括所有必需的
1 2 3 | go build Test.go someFile.go go run Test.go someFile.go |
1 | go build |
注意1:上面的命令引用本地软件包,因此必须从
注意2:尽管其他答案已经提出了有效的解决方案,但我还是决定在此处添加一些详细信息来帮助社区,因为这是开始使用Go时的常见问题:)