How to Compile a Go Program: Simple Steps
To compile a Go program, use the
go build command followed by your Go source file name. This creates an executable file you can run directly on your system.Syntax
The basic syntax to compile a Go program is:
go build [options] [file.go]
Here, go build is the command to compile, and file.go is your Go source file. The command creates an executable file in the current directory.
bash
go build main.go
Example
This example shows a simple Go program and how to compile it using go build. After compiling, you get an executable file to run.
go
package main import "fmt" func main() { fmt.Println("Hello, Go!") }
Output
Hello, Go!
Common Pitfalls
Common mistakes when compiling Go programs include:
- Not running
go buildin the directory with your source file. - Trying to run the source file directly without compiling.
- Missing the
mainpackage ormainfunction in your program.
Always ensure your Go file has a package main and a main() function to compile an executable.
go
package main // Missing main function import "fmt" func greet() { fmt.Println("Hi") } // Correct version: package main import "fmt" func main() { fmt.Println("Hi") }
Quick Reference
| Command | Description |
|---|---|
| go build main.go | Compile main.go into an executable |
| ./main | Run the compiled executable on Unix-like systems |
| main.exe | Run the compiled executable on Windows |
| go run main.go | Compile and run the program without creating an executable |
Key Takeaways
Use
go build filename.go to compile your Go program into an executable.Make sure your program has
package main and a main() function to compile successfully.Run the executable file created by
go build to see your program's output.You can also use
go run filename.go to compile and run in one step without creating an executable.