So far in our How To Code in Go series, you have used the command go run to automatically compile your source code and run the resulting executable. Although this command is useful for testing your code on the command line, distributing or deploying your application requires you to build your code into a shareable binary executable, or a single file containing machine byte code that can run your application. To do this, you can use the Go toolchain to build and install your program.
In Go, the process of translating source code into a binary executable is called building. Once this executable is built, it will contain not only your application, but also all the support code needed to execute the binary on the target platform. This means that a Go binary does not need system dependencies such as Go tooling to run on a new system. Putting these executables in an executable filepath on your own system will allow you to run the program from anywhere on your system. This is the same thing as installing the program onto your system.
Изучаем Golang. Урок №1. Установка Go, выбор IDE, первая программа
In this tutorial, you will use the Go toolchain to run, build, and install a sample Hello, World! program, allowing you to use, distribute, and deploy future applications effectively.
Prerequisites
To follow the example in this article, you will need:
- A Go workspace set up by following How To Install Go and Set Up a Local Programming Environment.
Step 1 — Setting Up and Running the Go Binary
First, create an application to use as an example for demonstrating the Go toolchain. To do this, you will use the classic “Hello, World!” program from the How To Write Your First Program in Go tutorial.
Create a directory called greeter in your src directory:
Next, move into the newly created directory and create the main.go file in the text editor of your choice:
Once the file is open, add the following contents:
src/greeter/main.go
package main import «fmt» func main() fmt.Println(«Hello, World!») >
When run, this program will print the phrase Hello, World! to the console, and then the program will exit successfully.
Save and exit the file.
To test the program, use the go run command, as you’ve done in previous tutorials:
You’ll receive the following output:
OutputHello, World!
As mentioned before, the go run command built your source file into an executable binary, and then ran the compiled program. However, this tutorial aims to build the binary in such a way that you can share and distribute it at will. To do this, you will use the go build command in the next step.
Step 2 — Creating a Go Module to Build a Go Binary
Go programs and libraries are built around the core concept of a module. A module contains information about the libraries that are used by your program and what versions of those libraries to use.
In order to tell Go that this is a Go module, you will need to create a Go module using the go mod command:
Установка языка программирования Go, среды разработки. Создание и компиляция первой программы
This will create the file go.mod , which will contain the name of the module and what version of Go was used to build it.
Outputgo: creating new go.mod: module greeter go: to add module requirements and sums: go mod tidy
Go will prompt you to run go mod tidy in order to update this module’s requirements if they change in the future. Running it now will have no additional effect.
Step 3 — Building Go Binaries With go build
Using go build , you can generate an executable binary for our sample Go application, allowing you to distribute and deploy the program where you want.
Try this with main.go . In your greeter directory, run the following command:
If you do not provide an argument to this command, go build will automatically compile the main.go program in your current directory. The command will include all your *.go files in the directory. It will also build all of the supporting code needed to be able to execute the binary on any computer with the same system architecture, regardless of whether that system has the .go source files, or even a Go installation.
In this case, you built your greeter application into an executable file that was added to your current directory. Check this by running the ls command:
If you are running macOS or Linux, you will find a new executable file that has been named after the directory in which you built your program:
Outputgreeter main.go go.mod
Note: On Windows, your executable will be greeter.exe .
By default go build will generate an executable for the current platform and architecture. For example, if built on a linux/386 system, the executable will be compatible with any other linux/386 system, even if Go is not installed. Go supports building for other platforms and architectures, which you can read more about in our Building Go Applications for Different Operating Systems and Architectures article.
Now, that you’ve created your executable, run it to make sure the binary has been built correctly. On macOS or Linux, run the following command:
The output of the binary will match the output from when you ran the program with go run :
OutputHello, World!
Now you have created a single executable binary that contains, not only your program, but also all of the system code needed to run that binary. You can now distribute this program to new systems or deploy it to a server, knowing that the file will always run the same program.
In the next section, this tutorial will explain how a binary is named and how you can change it, so that you can have better control over the build process of your program.
Step 4 — Changing the Binary Name
Now that you know how to generate an executable, the next step is to identify how Go chooses a name for the binary and to customize this name for your project.
When you run go build , the default is for Go to automatically decide on the name of the generated executable. It does this by using the module you created earlier. When the go mod init greeter command was run, it created the module with the name ‘greeter’, which is why the binary generated is named greeter in turn.
Let’s take a closer look at the module method. If you had a go.mod file in your project with a module declaration such as the following:
module github.com/sammy/shark
Then the default name for the generated executable would be shark .
In more complex programs that require specific naming conventions, these default values will not always be the best choice for naming your binary. In these cases, it would be best to customize your output with the -o flag.
To test this out, change the name of the executable you made in the last section to hello and have it placed in a sub-folder called bin . You don’t have to create this folder; Go will do that on its own during the build process.
Run the following go build command with the -o flag:
The -o flag makes Go match the output of the command to whatever argument you chose. In this case, the result is a new executable named hello in a sub-folder named bin .
To test the new executable, change into the new directory and run the binary:
You will receive the following output:
OutputHello, World!
You can now customize the name of your executable to fit the needs of your project, completing our survey of how to build binaries in Go. But with go build , you are still limited to running your binary from the current directory. In order to use newly built executables from anywhere on your system, you can install them using go install .
Step 5 — Installing Go Programs with go install
So far in this article, we have discussed how to generate executable binaries from our .go source files. These executables are helpful to distribute, deploy, and test, but they cannot yet be executed from outside of their source directories. This would be a problem if you wanted to actively use your program in shell scripts or in other workflows. To make the programs easier to use, you can install them into your system and access them from anywhere.
To understand what is meant by this, you will use the go install command to install your sample application.
The go install command behaves almost identically to go build , but instead of leaving the executable in the current directory, or a directory specified by the -o flag, it places the executable into the $GOPATH/bin directory.
To find where your $GOPATH directory is located, run the following command:
The output you receive will vary, but the default is the go directory inside of your $HOME directory:
Output$HOME/go
Since go install will place generated executables into a sub-directory of $GOPATH named bin , this directory must be added to the $PATH environment variable. This is covered in the Creating Your Go Workspace step of the prerequisite article How To Install Go and Set Up a Local Programming Environment.
With the $GOPATH/bin directory set up, move back to your greeter directory:
Now run the install command:
This will build your binary and place it in $GOPATH/bin . To test this, run the following:
This will list the contents of $GOPATH/bin :
Outputgreeter
Note: The go install command does not support the -o flag, so it will use the default name described earlier to name the executable.
With the binary installed, test to see if the program will run from outside its source directory. Move back to your home directory:
Use the following to run the program:
This will yield the following:
OutputHello, World!
Now you can take the programs you write and install them into your system, allowing you to use them from wherever, whenever you need them.
Conclusion
In this tutorial, you demonstrated how the Go toolchain makes it easy to build executable binaries from source code. These binaries can be distributed to run on other systems, even ones that do not have Go tooling and environments. You also used go install to automatically build and install our programs as executables in the system’s $PATH . With go build and go install , you now have the ability to share and use your application at will.
Now that you know the basics of go build , you can explore how to make modular source code with the Customizing Go Binaries with Build Tags tutorial, or how to build for different platforms with Building Go Applications for Different Operating Systems and Architectures. If you’d like to learn more about the Go programming language in general, check out the entire How To Code in Go series.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Code in Go
Go (or GoLang) is a modern programming language originally developed by Google that uses high-level syntax similar to scripting languages. It is popular for its minimal syntax and innovative handling of concurrency, as well as for the tools it provides for building native binaries on foreign platforms.
Browse Series: 53 articles
- 1/53 How To Code in Go eBook
- 2/53 How To Install Go and Set Up a Local Programming Environment on Ubuntu 18.04
- 3/53 How To Install Go and Set Up a Local Programming Environment on macOS
Источник: www.digitalocean.com
Как скомпилировать программу на GO
А можно поподробнее. Когда открою командную строку что прописывать. Если прописывать go build fileName.go. Пишет go не является внутренней или внешней командой.
1 июл 2013 в 5:21
Значит у вас путь к файлу go не прописан. Вот почитайте golang.org/doc/install
1 июл 2013 в 5:26
Спасибо с этим разобрался. Теперь пишет imports unicode: C:Gosrcpkgfmtformat.go:10:2: C:Gosrcpkgunicode: found packages unicode (casetables.go) and main (maketables.go)
1 июл 2013 в 8:00
Убедись что компилятор есть в PATH
Eсли есть то в папке с исходниками shif + пкм > открыть окно PowerShell здесь (или командную строку) > пишешь go build ./filename.go
вроде так
так же может помочь эта статья
Отслеживать
ответ дан 8 сен 2017 в 21:33
Yuriy Kosarikhin Yuriy Kosarikhin
55 8 8 бронзовых знаков
Запустить в среде Windows можно go run myProgram.go где ваша программа myProgram.go или C:Gobingo.exe run D:/go/myProgram.go . Скомпилировать и запустить можно с помощю команды go build — go build D:/go/myProgram.go
Отслеживать
121k 24 24 золотых знака 121 121 серебряный знак 293 293 бронзовых знака
ответ дан 7 авг 2017 в 20:13
39 3 3 бронзовых знака
Компилируется все именно так: go build fileName.go
Если вам нужно скомпилировать под все системы и если вы в linux, то я буквально сейчас написал на bash скрипт для компиляции под все OS.
cu=`pwd` rm -rf release/packages echo «success deletion» || echo «not success» mkdir -p release/packages/ os_all=’linux windows darwin freebsd’ arch_all=’386 amd64 arm arm64 mips64 mips64le mips mipsle’ for os in $os_all; do for arch in $arch_all; do set GOOS=$os set GOARCH=$arch if [ $os = «windows» ]; then go build -o $os»_»$arch».exe» echo «Success build for arch «$arch» and os «$os || echo «No problem» mv $os»_»$arch».exe» release/packages echo «Move success» || echo «Move not success» else go build -o $os»_»$arch echo «Success build for arch «$arch» and os «$os || echo «No problem» mv $os»_»$arch release/packages echo «Move success» || echo «Move not success» fi done done echo «Success Build» cd $cu
Просто создайте новый файл compile.sh, положите туда этот код и зайдите в терминал. С помощью cd перейдите в эту папку и напишите bash compile.sh
После этого ваш скрипт на Go будет скомпилирован под все системы. Найти готовые файлы можно будет в папке release/packages.
Источник: ru.stackoverflow.com
Как компилировать и устанавливать программы Go
Команда go run для автоматической компиляции исходного кода и запуска полученного исполняемого файла полезна для тестирования кода в командной строке, для развертывания или развертывания приложения необходимо создать код в совместно используемом двоичном исполняемом файле или в одном файле, содержащем машинный байт-код, который может запускать приложение. Для этого вы можете использовать набор инструментов Go для компиляции и установки программа.
В Go процесс перевода исходного кода в двоичный исполняемый файл называется сборкой. После того, как этот исполняемый файл будет создан, он будет содержать не только ваше приложение, но и весь вспомогательный код, необходимый для запуска двоичного файла на целевой платформе. Это означает, что бинарный файл Go не нуждается в системных зависимостях, таких как Go, для запуска в новой системе, в отличие от других языков, таких как Ruby, Python или Node.js. Поместив эти исполняемые файлы в путь к исполняемому файлу в вашей системе, вы сможете запускать программу из любого места в системе.
В этом руководстве мы будем использовать цепочку инструментов Go для запуска, создания и установки Hello, World! , что позволяет эффективно использовать и развертывать будущие приложения.
Предпосылки
Чтобы следовать примеру из этой статьи, в вашей системе должен быть установлен Go:
- Как установить Go на CentOS 8.
- Как установить Go на Linux Debian 10.
- Как установить Go на Ubuntu 18.04.
Установите и запустите Go Binary
Во-первых, давайте создадим приложение для использования в качестве примера для набора инструментов Go.Для этого мы будем использовать классический Hello, World! .
Создайте каталог с именем greeter в вашем каталоге src :
mkdir greeter
Затем перейдите в только что созданный каталог с помощью команды cd и создайте файл main.go в текстовом редакторе по вашему выбору:
cd greeter
nano main.go
После открытия файла добавьте следующее содержимое:
package main import «fmt» func main()
src/greeter/main.go
При запуске эта программа напечатает фразу Hello, World! на консоли, программа правильно закроется.
Сохраните и закройте файл.
Чтобы протестировать программу, используйте команду go run :
go run main.go
Вы получите следующий вывод:
Hello, World!
Как упоминалось выше, команда go run внедряла исходный файл в исполняемый двоичный файл, а затем запускала скомпилированную программу. Тем не менее, это руководство направлено на создание двоичного файла таким образом, чтобы вы могли делиться им и распространять его по своему усмотрению. Для этого на следующем шаге вы будете использовать команду go build .
Строительство дорожек с помощью go build
С помощью go build вы можете сгенерировать исполняемый двоичный файл для нашего примера приложения Go, что позволит вам развертывать и развертывать программу в любом месте.
Попробуйте это с main.go В вашем каталоге greeter выполните следующую команду:
go build
Если вы не укажете аргумент этой команде, go build автоматически создаст программу в текущем main.go Команда включит все ваши файлы *.go в каталоге. Он также соберет весь вспомогательный код, необходимый для запуска бинарного файла на любом компьютере с такой же системной архитектурой, независимо от того, есть ли в этой системе исходные файлы .go или даже установка Go.
В этом случае приложение greeter было создано в исполняемом файле, который был добавлен в текущий каталог. Проверьте это, выполнив команду ls :
Если вы используете macOS или Linux, вы найдете новый исполняемый файл, названный в честь каталога, в котором вы создали свою программу:
greeter main.go
Примечание. greeter.exe
По умолчанию go build создаст исполняемый файл для текущей платформы и архитектуры. Например, если он построен на системе linux/386 , исполняемый файл будет совместим с любой другой системой linux/386 , даже если Go не установлен.
Теперь, когда вы создали свой исполняемый файл, запустите его, чтобы убедиться, что двоичный файл был создан правильно. В macOS или Linux выполните следующую команду:
./greeter
В Windows запустите:
greeter.exe
Вывод двоичного файла будет соответствовать выводу, когда вы запустили программу с помощью go run :
Hello, World!
Теперь вы создали один исполняемый двоичный файл, который содержит не только вашу программу, но и весь системный код, необходимый для запуска этого двоичного файла. Теперь вы можете развернуть эту программу на новых системах или развернуть ее на сервере, зная, что файл всегда будет запускать одну и ту же программу.
В следующем разделе этого руководства объясняется, как называется двоичный файл и как его можно изменить, чтобы вы могли лучше контролировать процесс компиляции вашей программы.
Изменить бинарное имя
Теперь, когда вы знаете, как сгенерировать исполняемый файл, следующим шагом будет определение того, как Go выбирает имя для двоичного файла, и настройка этого имени для вашего проекта.
При запуске go build по умолчанию используется Go, чтобы автоматически выбрать имя сгенерированного исполняемого файла. Это делается двумя способами: если вы используете Go Modules, Go будет использовать последнюю часть имени вашего модуля; в противном случае Go будет использовать текущее имя каталога. Это метод, использованный в последнем разделе, когда каталог greeter был создан, изменен в нем, а затем запущен go build .
Давайте подробнее рассмотрим метод формы. Если бы в проекте был файл go.mod с объявлением module как показано ниже:
module github.com/noviello/shark
Таким образом, имя по умолчанию для сгенерированного исполняемого файла будет shark .
В более сложных программах, требующих определенных соглашений об именах, эти значения по умолчанию не всегда будут лучшим выбором для именования вашего двоичного файла. В таких случаях было бы лучше настроить вывод с флагом -o .
Чтобы попробовать, измените имя исполняемого файла, созданного в предыдущем разделе, на hello и поместите его в подпапку с именем bin . Нет необходимости создавать эту папку, Go сделает это сам в процессе сборки.
Запустите следующую команду go build с флагом -o :
go build -o bin/hello
Флаг -o заставляет Go сопоставлять вывод команды с любыми аргументами, которые вы выберете. В этом случае результатом является новый исполняемый файл с именем hello в подпапке с именем bin .
Чтобы протестировать новый исполняемый файл, перейдите в новый каталог и запустите двоичный файл:
cd bin
./hello
Вы получите следующий вывод:
Hello, World!
Теперь вы можете настроить имя исполняемого файла в соответствии с потребностями вашего проекта. Но с go build вы по-прежнему ограничены запуском бинарного файла из текущего каталога. Чтобы использовать исполняемые файлы из любого места в системе, вы можете установить их с помощью go install .
Установите программы Go с помощью go install
До сих пор в этой статье мы обсуждали, как создавать исполняемые двоичные файлы из наших исходных файлов .go . Эти исполняемые файлы полезны для распространения и тестирования, но их пока нельзя запускать за пределами их исходных каталогов. Это может быть проблемой, если вы хотите активно использовать программу, например, если вы разработали инструмент командной строки, чтобы помочь рабочему процессу в вашей системе. Чтобы упростить использование программ, вы можете установить их в своей системе и получать к ним доступ из любого места.
Чтобы понять, что это значит, мы воспользуемся командой go install для установки примера приложения.
Команда go install ведет себя почти так же, как и go build , но вместо того, чтобы оставить исполняемый файл в текущем каталоге или в каталоге, указанном флагом -o , она помещает исполняемый файл в $GOPATH/bin .
Чтобы узнать, где находится ваш каталог $GOPATH , выполните следующую команду:
go env GOPATH
Полученный вывод будет отличаться, но по умолчанию используется каталог go в каталоге $HOME :
$HOME/go
Поскольку go install поместит сгенерированные исполняемые файлы в подкаталог $GOPATH именем bin , этот каталог необходимо добавить в переменную окружения $PATH .
Установив каталог $GOPATH/bin , вернитесь в каталог greeter :
Теперь запустите команду установки:
go install
Это создаст ваш двоичный файл и вставит его $GOPATH/bin . Чтобы убедиться в этом, сделайте следующее:
ls $GOPATH/bin
Это перечислит содержимое $GOPATH/bin :
greeter
Примечание. go install не -o
Установив двоичный файл, проверьте, будет ли программа запускаться из-за пределов исходного каталога. Вернитесь в свой домашний каталог:
cd $HOME
Для запуска программы используйте следующее:
greeter
Это приведет к следующему:
Hello, World!
Теперь вы можете взять написанные вами программы и установить их в своей системе, что позволит вам использовать их где угодно и когда они вам понадобятся.
Вывод
В этом руководстве вы узнали, как набор инструментов Go упрощает создание исполняемых двоичных файлов из исходного кода. Эти двоичные файлы можно распространять для запуска в других системах, даже в тех, в которых нет инструментов и сред Go.Кроме того, go install автоматически создает и устанавливает наши программы в виде исполняемых файлов в системах $PATH . С go build and go install теперь у вас есть возможность поделиться своим приложением и использовать его по своему усмотрению.
Supportaci se ti piacciono i nostri contenuti. Grazie.
Noviello.it Newsletter
Ricevi gli ultimi approfondimenti direttamente nella tua casella di posta!
Источник: noviello.it