/

How to Compile and Run a Go Program

How to Compile and Run a Go Program

In this tutorial, we will build upon what we learned in our previous tutorial on how to create your first Go program. If you haven’t read it yet, you can find it here.

To compile and run a Go program, follow these steps:

  1. Open a terminal in the hello folder where your Go program is located.
  2. Use the go run command to compile and run the program. Enter the following command in the terminal:
1
go run hello.go
  1. The program will be compiled and executed. If everything goes well, you should see the output “Hello, World!” in the terminal.

Screen Shot 2022-07-28 at 12.18.23.png

By using the go run command, Go first compiles the program and then runs it.

If you want to create a binary executable of your Go program, you can use the go build command instead. This allows you to distribute the program to others who can run it without installing Go.

To create a binary executable, follow these steps:

  1. Open a terminal in the hello folder.
  2. Use the go build command followed by the name of your Go program file. Enter the following command in the terminal:
1
go build hello.go
  1. A binary file named hello will be created. This file is the executable version of your Go program.

Screen Shot 2022-07-28 at 12.19.50.png

Now, you can distribute this binary file to others, and they can run it directly without having Go installed on their machines. The binary is already packaged for execution.

The binary will run on the same architecture it was built on. However, if you want to create a binary for a different architecture, you can use the GOOS and GOARCH environment variables.

For example, to create a binary executable for 64-bit Windows machines, use the following command:

1
GOOS=windows GOARCH=amd64 go build hello.go

This will create a hello.exe executable.

Screen Shot 2022-07-28 at 15.36.55.png

Similarly, to create a binary for 64-bit macOS (Intel or Apple Silicon), use GOOS=darwin GOARCH=amd64. For Linux, use GOOS=linux GOARCH=amd64.

This flexibility to create binaries for different architectures is one of the great features of Go.

tags: [“Go programming”, “Go development”, “compile Go program”, “run Go program”, “build Go binary”, “distribute Go program”, “GOOS”, “GOARCH”]