Run code with multiple files in the same main package in GoLang

English 简体中文 繁体中文 ภาษาไทย Tiếng Việt
Summary

When developing Go programs with multiple files within the same main package, directly running `go run main.go` will fail to resolve symbols defined in other source files. To successfully execute such a program, especially when not within the GOPATH, developers have a few effective methods. On *nix systems, `go run *.go` can load all necessary files, though this command is not functional on Windows due to shell expansion differences. A more universal solution is `go run .`, which correctly processes all Go files in the current directory across all operating systems. Alternatively, `go build` generates a standalone executable binary, offering a convenient way to run the program directly after compilation.

To run a GoLang program, there needs to be a main() function defined. In some cases when developing some demo program which has multiple files and just wanna put them in the same main package and this folder is not in GOPATH, how to run the program?

Let's say we have following folder structure where the main() function is defined in main.go.

If you just run below command, it would fail to start to run the program and gives some error if some struct is defined in other files and being used.

PS D:\Project\Go\sourcecode_updater\v2> go run main.go
# command-line-arguments
.\main.go:35:11: undefined: Pool
.\main.go:76:12: undefined: UpdateJob

There are a few ways to run the program successfully.

go run *.go

In some *nix operating systems including Linux and MacOS, can run go run *.go which will load all go files in the package and run the main().

But this command doesn't work on Windows as token expansion doesn't work in the windows command line.

PS D:\Project\Go\sourcecode_updater\v2> go run *.go
CreateFile *.go: The filename, directory name, or volume label syntax is incorrect.

go run .

Similar to above command, this command will also try to load all files in current folder and run the main() function and it can work on Windows as well.

PS D:\Project\Go\sourcecode_updater\v2> go run .
all workers started
2021/05/15 23:15:54 start fetching posts to process
2021/05/15 23:15:54 start to process batch 1

go build

GoLang provides a very convenient and quick way to generate a executable binary so that it can be ran easily as well with go build command. 

PS D:\Project\Go\sourcecode_updater\v2> go build -o main.exe
PS D:\Project\Go\sourcecode_updater\v2> ./main
all workers started
2021/05/15 23:17:29 start fetching posts to process
2021/05/15 23:17:29 start to process batch 1

This is the beauty of GoLang.

GOLANG EXECUTABLE MAIN PACKAGE MULTIPLE FILE

  RELATED

  COMMENTS

0

No comment for this article.