Home Backend Development Golang How to compile golang

How to compile golang

Dec 26, 2019 am 09:43 AM
golang

How to compile golang

The go build command used in Go language is mainly used to compile code. During the compilation process of the package, if necessary, the packages associated with it will be compiled at the same time.

go build has many compilation methods, such as no-parameter compilation, file list compilation, specified package compilation, etc. You can use these methods to output executable files.

go build No parameter compilation

The directory relationship of the code relative to GOPATH is as follows:

.
└── src
└── chapter11
└── gobuild
├── lib.go
└── └── main.go

main.go code is as follows:

package main

import (
    "fmt"
)

func main() {

    // 同包的函数
    pkgFunc()

    fmt.Println("hello world")
}

lib.go code is as follows:

package main
import "fmt"
func pkgFunc() {
    fmt.Println("call pkgFunc")
}

If there are no package references that depend on GOPATH in the source code, then these source codes can use parameterless go build. The format is as follows:

go build

Use the go build command in the directory where the code is located (./src/chapter11/gobuild), as shown below:

$ cd src/chapter11/gobuild/
$ go build
$ ls
gobuild lib.go main.go
$ ./gobuild
call pkgFunc
hello world

Command line instructions And the output description is as follows:

Line 1, go to the source code directory of this example.

Line 2, go build will search the go source code of the current directory when compilation starts. In this example, go build will find two files, lib.go and main.go. After compiling these two files, an executable file with the current directory name is generated and placed in the current directory. The executable file here is go build.

Lines 3 and 4 list the files in the current directory. The compilation is successful and the go build executable file is output.

Line 5, run the executable file go build in the current directory.

Lines 6 and 7, the output content after executing go build.

go build file list

When compiling multiple source code files in the same directory, you can provide multiple file names after go build, and go build will compile these source codes. , output the executable file, the format of "go build file list" is as follows:

go build file1.go file2.go……

Use go build in the directory where the code is located (./src/chapter11/gobuild), and add the file to be compiled after go build Source file name, the code is as follows:

$ go build main.go lib.go
$ ls
lib.go main main.go
$ ./main
call pkgFunc
hello world
$ go build lib.go main.go
$ ls
lib lib.go main main.go

Command line instructions The output description is as follows:

In line 1, add the file list after go build and select the Go source code that needs to be compiled.

Lines 2 and 3 list the files in the current directory after compilation. This time the executable file name becomes main.

Lines 4 to 6 execute the main file and get the expected output.

Line 7, try to adjust the order of the file list and put lib.go at the top of the list.

On lines 8 and 9, the lib executable file appears in the compilation result.

When compiling using the "go build file list" method, the executable file selects the first source code file in the file list as the executable file name for output by default.

go build package

After setting GOPATH, "go build package" can be compiled directly based on the package name, even if the files in the package are added (added) or deleted ( Except) does not affect compilation directives.

1) The directory relationship between the code location and source code

relative to GOPATH is as follows:

.
└── src
└── chapter11
└ ─ ├ ──Main.go
# ─ ─ mypkg
—— mypkg.go

## code is as follows:
package main
import (
    "chapter11/goinstall/mypkg"
    "fmt"
)
func main() {
    mypkg.CustomPkgFunc()
    fmt.Println("hello world")
}

mypkg.go code is as follows:

package mypkg
import "fmt"
func CustomPkgFunc() {
    fmt.Println("call CustomPkgFunc")
}

2) Compile command by package

Execute the following command to compile goinstall code by package:

$ export GOPATH=/home/davy/golangbook/code
$ go build -o main chapter11/goinstall

$ ./goinstall
call CustomPkgFunc
hello world

code The instructions are as follows:

Line 1, set the environment variable GOPATH. The path here is the author's directory. You can set GOPATH according to the actual directory.

Line 2, -o execution specifies the output file as main, followed by the name of the package to be compiled. Package names start relative to the src directory under GOPATH.

Lines 3 to 5, the compilation is successful, and the expected output is obtained after executing main.

For more golang knowledge, please pay attention to the golang tutorial column.

The above is the detailed content of How to compile golang. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
Understanding the Performance Differences Between Golang and Python for Web APIs Understanding the Performance Differences Between Golang and Python for Web APIs Jul 03, 2025 am 02:40 AM

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

Memory Footprint Comparison: Running Identical Web Service Workloads in Golang and Python Memory Footprint Comparison: Running Identical Web Service Workloads in Golang and Python Jul 03, 2025 am 02:32 AM

GousessignificantlylessmemorythanPythonwhenrunningwebservicesduetolanguagedesignandconcurrencymodeldifferences.1.Go'sgoroutinesarelightweightwithminimalstackoverhead,allowingefficienthandlingofthousandsofconnections.2.Itsgarbagecollectorisoptimizedfo

The State of Machine Learning Libraries: Golang's Offerings vs the Extensive Python Ecosystem The State of Machine Learning Libraries: Golang's Offerings vs the Extensive Python Ecosystem Jul 03, 2025 am 02:00 AM

Pythonisthedominantlanguageformachinelearningduetoitsmatureecosystem,whileGoofferslightweighttoolssuitedforspecificusecases.PythonexcelswithlibrarieslikeTensorFlow,PyTorch,Scikit-learn,andPandas,makingitidealforresearch,prototyping,anddeployment.Go,d

Understanding Memory Management Differences: Golang's GC vs Python's Reference Counting Understanding Memory Management Differences: Golang's GC vs Python's Reference Counting Jul 03, 2025 am 02:31 AM

The core difference between Go and Python in memory management is the different garbage collection mechanisms. Go uses concurrent mark clearance (MarkandSweep) GC, which automatically runs and executes concurrently with program logic, effectively deals with circular references. It is suitable for high concurrency scenarios, but cannot accurately control the recycling time; while Python mainly relies on reference counting, and object references are immediately released when zeroed. The advantage is that they are instant recycling and simple implementation, but there is a circular reference problem, so they need to use the GC module to assist in cleaning. In actual development, Go is more suitable for high-performance server programs, while Python is suitable for script classes or applications with low performance requirements.

Golang pointer to interface explanation Golang pointer to interface explanation Jul 21, 2025 am 03:14 AM

An interface is not a pointer type, it contains two pointers: dynamic type and value. 1. The interface variable stores the type descriptor and data pointer of the specific type; 2. When assigning the pointer to the interface, it stores a copy of the pointer, and the interface itself is not a pointer type; 3. Whether the interface is nil requires the type and value to be judged at the same time; 4. When the method receiver is a pointer, only the pointer type can realize the interface; 5. In actual development, pay attention to the difference between the value copy and pointer transfer of the interface. Understanding these can avoid runtime errors and improve code security.

Comparing the Standard Libraries: Key Differences Between Golang and Python Comparing the Standard Libraries: Key Differences Between Golang and Python Jul 03, 2025 am 02:29 AM

Golang and Python's standard libraries differ significantly in design philosophy, performance and concurrency support, developer experience, and web development capabilities. 1. In terms of design philosophy, Go emphasizes simplicity and consistency, providing a small but efficient package; while Python follows the concept of "bringing its own battery" and provides rich modules to enhance flexibility. 2. In terms of performance and concurrency, Go natively supports coroutines and channels, which are suitable for high concurrency scenarios; Python is limited by GIL, and multithreading cannot achieve true parallelism and needs to rely on heavier multi-process modules. 3. In terms of developer experience, Go toolchain forces code formatting and standardized import to improve team collaboration consistency; Python provides more freedom but can easily lead to style confusion. 4. Web development

How to run shell command in golang How to run shell command in golang Jul 07, 2025 am 12:47 AM

Execute Shell commands in Go language can be implemented through the standard library os/exec. The basic method is to use exec.Command() to create a command object and call Output() to get the result; 1. Create a command object when executing a simple command and call Output() to get the output; 2. When real-time output is required, use StdoutPipe and StderrPipe to execute and print while executing; 3. For complex commands containing pipelines or redirects, they can be handed over to /bin/sh-c for analysis and processing; 4. In terms of security, avoid splicing user input, and it is recommended to pass a parameter list; 5. The control command background operation can be achieved by combining Start() and Wait();

Migrating a Python Web Application Monolith to Golang Microservices Architecture Migrating a Python Web Application Monolith to Golang Microservices Architecture Jul 03, 2025 am 01:53 AM

The core of migrating to Golang microservices architecture is to clarify service boundaries, select communication modes, manage data flows, and optimize deployment monitoring. First, independent services are defined by identifying business logic boundaries such as user management, payment and other modules, and the principles of high cohesion and low coupling and domain-driven design are followed; second, REST, gRPC or message queues are selected as communication methods according to needs, such as using event asynchronous notifications instead of direct calls; then, each service independently manages the database and exchanges data through API or event, and uses CQRS or Saga to process distributed transactions; finally, Docker containerization and Kubernetes orchestration and deployment services are used to combine logs, metrics and tracking tools to achieve comprehensive observability.

See all articles