0
0
GoHow-ToBeginner · 3 min read

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 build in the directory with your source file.
  • Trying to run the source file directly without compiling.
  • Missing the main package or main function 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

CommandDescription
go build main.goCompile main.go into an executable
./mainRun the compiled executable on Unix-like systems
main.exeRun the compiled executable on Windows
go run main.goCompile 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.