summaryrefslogtreecommitdiff
path: root/devdocs/go/go%2Fbuild%2Findex.html
blob: 68a204ff27039fe7ec2fe42976c730b6602c51eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<h1> Package build  </h1>     <ul id="short-nav">
<li><code>import "go/build"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-subdirectories">Subdirectories</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package build gathers information about Go packages. </p>
<h3 id="hdr-Go_Path">Go Path</h3> <p>The Go path is a list of directory trees containing Go source code. It is consulted to resolve imports that cannot be found in the standard Go tree. The default path is the value of the GOPATH environment variable, interpreted as a path list appropriate to the operating system (on Unix, the variable is a colon-separated string; on Windows, a semicolon-separated string; on Plan 9, a list). </p>
<p>Each directory listed in the Go path must have a prescribed structure: </p>
<p>The src/ directory holds source code. The path below 'src' determines the import path or executable name. </p>
<p>The pkg/ directory holds installed package objects. As in the Go tree, each target operating system and architecture pair has its own subdirectory of pkg (pkg/GOOS_GOARCH). </p>
<p>If DIR is a directory listed in the Go path, a package with source in DIR/src/foo/bar can be imported as "foo/bar" and has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a" (or, for gccgo, "DIR/pkg/gccgo/foo/libbar.a"). </p>
<p>The bin/ directory holds compiled commands. Each command is named for its source directory, but only using the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The foo/ is stripped so that you can add DIR/bin to your PATH to get at the installed commands. </p>
<p>Here's an example directory layout: </p>
<pre data-language="go">GOPATH=/home/user/gocode

/home/user/gocode/
    src/
        foo/
            bar/               (go code in package bar)
                x.go
            quux/              (go code in package main)
                y.go
    bin/
        quux                   (installed command)
    pkg/
        linux_amd64/
            foo/
                bar.a          (installed package object)
</pre> <h3 id="hdr-Build_Constraints">Build Constraints</h3> <p>A build constraint, also known as a build tag, is a condition under which a file should be included in the package. Build constraints are given by a line comment that begins </p>
<pre data-language="go">//go:build
</pre> <p>Build constraints may also be part of a file's name (for example, source_windows.go will only be included if the target operating system is windows). </p>
<p>See 'go help buildconstraint' (<a href="https://golang.org/cmd/go/#hdr-Build_constraints">https://golang.org/cmd/go/#hdr-Build_constraints</a>) for details. </p>
<h3 id="hdr-Binary_Only_Packages">Binary-Only Packages</h3> <p>In Go 1.12 and earlier, it was possible to distribute packages in binary form without including the source code used for compiling the package. The package was distributed with a source file not excluded by build constraints and containing a "//go:binary-only-package" comment. Like a build constraint, this comment appeared at the top of a file, preceded only by blank lines and other line comments and with a blank line following the comment, to separate it from the package documentation. Unlike build constraints, this comment is only recognized in non-test Go source files. </p>
<p>The minimal source code for a binary-only package was therefore: </p>
<pre data-language="go">//go:binary-only-package

package mypkg
</pre> <p>The source code could include additional Go code. That code was never compiled but would be processed by tools like godoc and might be useful as end-user documentation. </p>
<p>"go build" and other commands no longer support binary-only-packages. <a href="#Import">Import</a> and <a href="#ImportDir">ImportDir</a> will still set the BinaryOnly flag in packages containing these comments for use in tools and error messages. </p>     <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#pkg-variables">Variables</a></li>
<li><a href="#ArchChar">func ArchChar(goarch string) (string, error)</a></li>
<li><a href="#IsLocalImport">func IsLocalImport(path string) bool</a></li>
<li><a href="#Context">type Context</a></li>
<li> <a href="#Context.Import">func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error)</a>
</li>
<li> <a href="#Context.ImportDir">func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error)</a>
</li>
<li> <a href="#Context.MatchFile">func (ctxt *Context) MatchFile(dir, name string) (match bool, err error)</a>
</li>
<li> <a href="#Context.SrcDirs">func (ctxt *Context) SrcDirs() []string</a>
</li>
<li><a href="#Directive">type Directive</a></li>
<li><a href="#ImportMode">type ImportMode</a></li>
<li><a href="#MultiplePackageError">type MultiplePackageError</a></li>
<li> <a href="#MultiplePackageError.Error">func (e *MultiplePackageError) Error() string</a>
</li>
<li><a href="#NoGoError">type NoGoError</a></li>
<li> <a href="#NoGoError.Error">func (e *NoGoError) Error() string</a>
</li>
<li><a href="#Package">type Package</a></li>
<li> <a href="#Import">func Import(path, srcDir string, mode ImportMode) (*Package, error)</a>
</li>
<li> <a href="#ImportDir">func ImportDir(dir string, mode ImportMode) (*Package, error)</a>
</li>
<li> <a href="#Package.IsCommand">func (p *Package) IsCommand() bool</a>
</li>
</ul> <h3>Package files</h3> <p>  <span>build.go</span> <span>doc.go</span> <span>gc.go</span> <span>read.go</span> <span>syslist.go</span> <span>zcgo.go</span>  </p>   <h2 id="pkg-variables">Variables</h2> <p>ToolDir is the directory containing build tools. </p>
<pre data-language="go">var ToolDir = getToolDir()</pre> <h2 id="ArchChar">func <span>ArchChar</span>  </h2> <pre data-language="go">func ArchChar(goarch string) (string, error)</pre> <p>ArchChar returns "?" and an error. In earlier versions of Go, the returned string was used to derive the compiler and linker tool names, the default object file suffix, and the default linker output name. As of Go 1.5, those strings no longer vary by architecture; they are compile, link, .o, and a.out, respectively. </p>
<h2 id="IsLocalImport">func <span>IsLocalImport</span>  </h2> <pre data-language="go">func IsLocalImport(path string) bool</pre> <p>IsLocalImport reports whether the import path is a local import path, like ".", "..", "./foo", or "../foo". </p>
<h2 id="Context">type <span>Context</span>  </h2> <p>A Context specifies the supporting context for a build. </p>
<pre data-language="go">type Context struct {
    GOARCH string // target architecture
    GOOS   string // target operating system
    GOROOT string // Go root
    GOPATH string // Go paths

    // Dir is the caller's working directory, or the empty string to use
    // the current directory of the running process. In module mode, this is used
    // to locate the main module.
    //
    // If Dir is non-empty, directories passed to Import and ImportDir must
    // be absolute.
    Dir string // Go 1.14

    CgoEnabled  bool   // whether cgo files are included
    UseAllFiles bool   // use files regardless of go:build lines, file names
    Compiler    string // compiler to assume when computing target paths

    // The build, tool, and release tags specify build constraints
    // that should be considered satisfied when processing go:build lines.
    // Clients creating a new context may customize BuildTags, which
    // defaults to empty, but it is usually an error to customize ToolTags or ReleaseTags.
    // ToolTags defaults to build tags appropriate to the current Go toolchain configuration.
    // ReleaseTags defaults to the list of Go releases the current release is compatible with.
    // BuildTags is not set for the Default build Context.
    // In addition to the BuildTags, ToolTags, and ReleaseTags, build constraints
    // consider the values of GOARCH and GOOS as satisfied tags.
    // The last element in ReleaseTags is assumed to be the current release.
    BuildTags   []string
    ToolTags    []string // Go 1.17
    ReleaseTags []string // Go 1.1

    // The install suffix specifies a suffix to use in the name of the installation
    // directory. By default it is empty, but custom builds that need to keep
    // their outputs separate can set InstallSuffix to do so. For example, when
    // using the race detector, the go command uses InstallSuffix = "race", so
    // that on a Linux/386 system, packages are written to a directory named
    // "linux_386_race" instead of the usual "linux_386".
    InstallSuffix string // Go 1.1

    // JoinPath joins the sequence of path fragments into a single path.
    // If JoinPath is nil, Import uses filepath.Join.
    JoinPath func(elem ...string) string

    // SplitPathList splits the path list into a slice of individual paths.
    // If SplitPathList is nil, Import uses filepath.SplitList.
    SplitPathList func(list string) []string

    // IsAbsPath reports whether path is an absolute path.
    // If IsAbsPath is nil, Import uses filepath.IsAbs.
    IsAbsPath func(path string) bool

    // IsDir reports whether the path names a directory.
    // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method.
    IsDir func(path string) bool

    // HasSubdir reports whether dir is lexically a subdirectory of
    // root, perhaps multiple levels below. It does not try to check
    // whether dir exists.
    // If so, HasSubdir sets rel to a slash-separated path that
    // can be joined to root to produce a path equivalent to dir.
    // If HasSubdir is nil, Import uses an implementation built on
    // filepath.EvalSymlinks.
    HasSubdir func(root, dir string) (rel string, ok bool)

    // ReadDir returns a slice of fs.FileInfo, sorted by Name,
    // describing the content of the named directory.
    // If ReadDir is nil, Import uses os.ReadDir.
    ReadDir func(dir string) ([]fs.FileInfo, error)

    // OpenFile opens a file (not a directory) for reading.
    // If OpenFile is nil, Import uses os.Open.
    OpenFile func(path string) (io.ReadCloser, error)
}
</pre> <p>Default is the default Context for builds. It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables if set, or else the compiled code's GOARCH, GOOS, and GOROOT. </p>
<pre data-language="go">var Default Context = defaultContext()</pre> <h3 id="Context.Import">func (*Context) <span>Import</span>  </h3> <pre data-language="go">func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error)</pre> <p>Import returns details about the Go package named by the import path, interpreting local import paths relative to the srcDir directory. If the path is a local import path naming a package that can be imported using a standard import path, the returned package will set p.ImportPath to that path. </p>
<p>In the directory containing the package, .go, .c, .h, and .s files are considered part of the package except for: </p>
<ul> <li>.go files in package documentation </li>
<li>files starting with _ or . (likely editor temporary files) </li>
<li>files with build constraints not satisfied by the context </li>
</ul> <p>If an error occurs, Import returns a non-nil error and a non-nil *<a href="#Package">Package</a> containing partial information. </p>
<h3 id="Context.ImportDir">func (*Context) <span>ImportDir</span>  </h3> <pre data-language="go">func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error)</pre> <p>ImportDir is like <a href="#Import">Import</a> but processes the Go package found in the named directory. </p>
<h3 id="Context.MatchFile">func (*Context) <span>MatchFile</span>  <span title="Added in Go 1.2">1.2</span> </h3> <pre data-language="go">func (ctxt *Context) MatchFile(dir, name string) (match bool, err error)</pre> <p>MatchFile reports whether the file with the given name in the given directory matches the context and would be included in a <a href="#Package">Package</a> created by <a href="#ImportDir">ImportDir</a> of that directory. </p>
<p>MatchFile considers the name of the file and may use ctxt.OpenFile to read some or all of the file's content. </p>
<h3 id="Context.SrcDirs">func (*Context) <span>SrcDirs</span>  </h3> <pre data-language="go">func (ctxt *Context) SrcDirs() []string</pre> <p>SrcDirs returns a list of package source root directories. It draws from the current Go root and Go path but omits directories that do not exist. </p>
<h2 id="Directive">type <span>Directive</span>  <span title="Added in Go 1.21">1.21</span> </h2> <p>A Directive is a Go directive comment (//go:zzz...) found in a source file. </p>
<pre data-language="go">type Directive struct {
    Text string         // full line comment including leading slashes
    Pos  token.Position // position of comment
}
</pre> <h2 id="ImportMode">type <span>ImportMode</span>  </h2> <p>An ImportMode controls the behavior of the Import method. </p>
<pre data-language="go">type ImportMode uint</pre> <pre data-language="go">const (
    // If FindOnly is set, Import stops after locating the directory
    // that should contain the sources for a package. It does not
    // read any files in the directory.
    FindOnly ImportMode = 1 &lt;&lt; iota

    // If AllowBinary is set, Import can be satisfied by a compiled
    // package object without corresponding sources.
    //
    // Deprecated:
    // The supported way to create a compiled-only package is to
    // write source code containing a //go:binary-only-package comment at
    // the top of the file. Such a package will be recognized
    // regardless of this flag setting (because it has source code)
    // and will have BinaryOnly set to true in the returned Package.
    AllowBinary

    // If ImportComment is set, parse import comments on package statements.
    // Import returns an error if it finds a comment it cannot understand
    // or finds conflicting comments in multiple source files.
    // See golang.org/s/go14customimport for more information.
    ImportComment

    // By default, Import searches vendor directories
    // that apply in the given source directory before searching
    // the GOROOT and GOPATH roots.
    // If an Import finds and returns a package using a vendor
    // directory, the resulting ImportPath is the complete path
    // to the package, including the path elements leading up
    // to and including "vendor".
    // For example, if Import("y", "x/subdir", 0) finds
    // "x/vendor/y", the returned package's ImportPath is "x/vendor/y",
    // not plain "y".
    // See golang.org/s/go15vendor for more information.
    //
    // Setting IgnoreVendor ignores vendor directories.
    //
    // In contrast to the package's ImportPath,
    // the returned package's Imports, TestImports, and XTestImports
    // are always the exact import paths from the source files:
    // Import makes no attempt to resolve or check those paths.
    IgnoreVendor
)</pre> <h2 id="MultiplePackageError">type <span>MultiplePackageError</span>  <span title="Added in Go 1.4">1.4</span> </h2> <p>MultiplePackageError describes a directory containing multiple buildable Go source files for multiple packages. </p>
<pre data-language="go">type MultiplePackageError struct {
    Dir      string   // directory containing files
    Packages []string // package names found
    Files    []string // corresponding files: Files[i] declares package Packages[i]
}
</pre> <h3 id="MultiplePackageError.Error">func (*MultiplePackageError) <span>Error</span>  <span title="Added in Go 1.4">1.4</span> </h3> <pre data-language="go">func (e *MultiplePackageError) Error() string</pre> <h2 id="NoGoError">type <span>NoGoError</span>  </h2> <p>NoGoError is the error used by <a href="#Import">Import</a> to describe a directory containing no buildable Go source files. (It may still contain test files, files hidden by build tags, and so on.) </p>
<pre data-language="go">type NoGoError struct {
    Dir string
}
</pre> <h3 id="NoGoError.Error">func (*NoGoError) <span>Error</span>  </h3> <pre data-language="go">func (e *NoGoError) Error() string</pre> <h2 id="Package">type <span>Package</span>  </h2> <p>A Package describes the Go package found in a directory. </p>
<pre data-language="go">type Package struct {
    Dir           string   // directory containing package sources
    Name          string   // package name
    ImportComment string   // path in import comment on package statement; added in Go 1.4
    Doc           string   // documentation synopsis
    ImportPath    string   // import path of package ("" if unknown)
    Root          string   // root of Go tree where this package lives
    SrcRoot       string   // package source root directory ("" if unknown)
    PkgRoot       string   // package install root directory ("" if unknown)
    PkgTargetRoot string   // architecture dependent install root directory ("" if unknown); added in Go 1.5
    BinDir        string   // command install directory ("" if unknown)
    Goroot        bool     // package found in Go root
    PkgObj        string   // installed .a file
    AllTags       []string // tags that can influence file selection in this directory; added in Go 1.2
    ConflictDir   string   // this directory shadows Dir in $GOPATH; added in Go 1.2
    BinaryOnly    bool     // cannot be rebuilt from source (has //go:binary-only-package comment); added in Go 1.7

    // Source files
    GoFiles           []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
    CgoFiles          []string // .go source files that import "C"
    IgnoredGoFiles    []string // .go source files ignored for this build (including ignored _test.go files); added in Go 1.1
    InvalidGoFiles    []string // .go source files with detected problems (parse error, wrong package name, and so on); added in Go 1.6
    IgnoredOtherFiles []string // non-.go source files ignored for this build; added in Go 1.16
    CFiles            []string // .c source files
    CXXFiles          []string // .cc, .cpp and .cxx source files; added in Go 1.2
    MFiles            []string // .m (Objective-C) source files; added in Go 1.3
    HFiles            []string // .h, .hh, .hpp and .hxx source files
    FFiles            []string // .f, .F, .for and .f90 Fortran source files; added in Go 1.7
    SFiles            []string // .s source files
    SwigFiles         []string // .swig files; added in Go 1.1
    SwigCXXFiles      []string // .swigcxx files; added in Go 1.1
    SysoFiles         []string // .syso system object files to add to archive

    // Cgo directives
    CgoCFLAGS    []string // Cgo CFLAGS directives
    CgoCPPFLAGS  []string // Cgo CPPFLAGS directives; added in Go 1.2
    CgoCXXFLAGS  []string // Cgo CXXFLAGS directives; added in Go 1.2
    CgoFFLAGS    []string // Cgo FFLAGS directives; added in Go 1.7
    CgoLDFLAGS   []string // Cgo LDFLAGS directives
    CgoPkgConfig []string // Cgo pkg-config directives

    // Test information
    TestGoFiles  []string // _test.go files in package
    XTestGoFiles []string // _test.go files outside package

    // Go directive comments (//go:zzz...) found in source files.
    Directives      []Directive // Go 1.21
    TestDirectives  []Directive // Go 1.21
    XTestDirectives []Directive // Go 1.21

    // Dependency information
    Imports        []string                    // import paths from GoFiles, CgoFiles
    ImportPos      map[string][]token.Position // line information for Imports
    TestImports    []string                    // import paths from TestGoFiles
    TestImportPos  map[string][]token.Position // line information for TestImports
    XTestImports   []string                    // import paths from XTestGoFiles
    XTestImportPos map[string][]token.Position // line information for XTestImports

    // //go:embed patterns found in Go source files
    // For example, if a source file says
    //	//go:embed a* b.c
    // then the list will contain those two strings as separate entries.
    // (See package embed for more details about //go:embed.)
    EmbedPatterns        []string                    // patterns from GoFiles, CgoFiles; added in Go 1.16
    EmbedPatternPos      map[string][]token.Position // line information for EmbedPatterns; added in Go 1.16
    TestEmbedPatterns    []string                    // patterns from TestGoFiles; added in Go 1.16
    TestEmbedPatternPos  map[string][]token.Position // line information for TestEmbedPatterns; added in Go 1.16
    XTestEmbedPatterns   []string                    // patterns from XTestGoFiles; added in Go 1.16
    XTestEmbedPatternPos map[string][]token.Position // line information for XTestEmbedPatternPos; added in Go 1.16
}
</pre> <h3 id="Import">func <span>Import</span>  </h3> <pre data-language="go">func Import(path, srcDir string, mode ImportMode) (*Package, error)</pre> <p>Import is shorthand for Default.Import. </p>
<h3 id="ImportDir">func <span>ImportDir</span>  </h3> <pre data-language="go">func ImportDir(dir string, mode ImportMode) (*Package, error)</pre> <p>ImportDir is shorthand for Default.ImportDir. </p>
<h3 id="Package.IsCommand">func (*Package) <span>IsCommand</span>  </h3> <pre data-language="go">func (p *Package) IsCommand() bool</pre> <p>IsCommand reports whether the package is considered a command to be installed (not just a library). Packages named "main" are treated as commands. </p>
<h2 id="pkg-subdirectories">Subdirectories</h2> <div class="pkg-dir"> <table> <tr> <th class="pkg-name">Name</th> <th class="pkg-synopsis">Synopsis</th> </tr> <tr> <td colspan="2"><a href="../index">..</a></td> </tr> <tr> <td class="pkg-name"> <a href="constraint/index">constraint</a> </td> <td class="pkg-synopsis"> Package constraint implements parsing and evaluation of build constraint lines. </td> </tr> </table> </div><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/go/build/" class="_attribution-link">http://golang.org/pkg/go/build/</a>
  </p>
</div>