Movatterモバイル変換


[0]ホーム

URL:


compile

commandstandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:18Imported by:0

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Compile, typically invoked as “go tool compile,” compiles a single Go packagecomprising the files named on the command line. It then writes a singleobject file named for the basename of the first source file with a .o suffix.The object file can then be combined with other objects into a package archiveor passed directly to the linker (“go tool link”). If invoked with -pack, the compilerwrites an archive directly, bypassing the intermediate object file.

The generated files contain type information about the symbols exported bythe package and about types used by symbols imported by the package fromother packages. It is therefore not necessary when compiling client C ofpackage P to read the files of P's dependencies, only the compiled output of P.

Command Line

Usage:

go tool compile [flags] file...

The specified files must be Go source files and all part of the same package.The same compiler is used for all target operating systems and architectures.The GOOS and GOARCH environment variables set the desired target.

Flags:

-D pathSet relative path for local imports.-I dir1 -I dir2Search for imported packages in dir1, dir2, etc,after consulting $GOROOT/pkg/$GOOS_$GOARCH.-LShow complete file path in error messages.-NDisable optimizations.-SPrint assembly listing to standard output (code only).-S -SPrint assembly listing to standard output (code and data).-VPrint compiler version and exit.-asmhdr fileWrite assembly header to file.-asanInsert calls to C/C++ address sanitizer.-buildid idRecord id as the build id in the export metadata.-blockprofile fileWrite block profile for the compilation to file.-c intConcurrency during compilation. Set 1 for no concurrency (default is 1).-completeAssume package has no non-Go components.-cpuprofile fileWrite a CPU profile for the compilation to file.-dynlinkAllow references to Go symbols in shared libraries (experimental).-eRemove the limit on the number of errors reported (default limit is 10).-embedcfg fileRead go:embed configuration from file.This is required if any //go:embed directives are used.The file is a JSON file mapping patterns to lists of filenamesand filenames to full path names.-goversion stringSpecify required go tool version of the runtime.Exits when the runtime go version does not match goversion.-hHalt with a stack trace at the first error detected.-importcfg fileRead import configuration from file.In the file, set importmap, packagefile to specify import resolution.-installsuffix suffixLook for packages in $GOROOT/pkg/$GOOS_$GOARCH_suffixinstead of $GOROOT/pkg/$GOOS_$GOARCH.-lDisable inlining.-lang versionSet language version to compile, as in -lang=go1.12.Default is current version.-linkobj fileWrite linker-specific object to file and compiler-specificobject to usual output file (as specified by -o).Without this flag, the -o output is a combination of bothlinker and compiler input.-mPrint optimization decisions. Higher values or repetitionproduce more detail.-memprofile fileWrite memory profile for the compilation to file.-memprofilerate rateSet runtime.MemProfileRate for the compilation to rate.-msanInsert calls to C/C++ memory sanitizer.-mutexprofile fileWrite mutex profile for the compilation to file.-nolocalimportsDisallow local (relative) imports.-o fileWrite object to file (default file.o or, with -pack, file.a).-p pathSet expected package import path for the code being compiled,and diagnose imports that would cause a circular dependency.-packWrite a package (archive) file rather than an object file-raceCompile with race detector enabled.-sWarn about composite literals that can be simplified.-sharedGenerate code that can be linked into a shared library.-spectre listEnable spectre mitigations in list (all, index, ret).-traceprofile fileWrite an execution trace to file.-trimpath prefixRemove prefix from recorded source file paths.

Flags related to debugging information:

-dwarfGenerate DWARF symbols.-dwarflocationlistsAdd location lists to DWARF in optimized mode.-gendwarfinl intGenerate DWARF inline info records (default 2).

Flags to debug the compiler itself:

-EDebug symbol export.-KDebug missing line numbers.-d listPrint debug information about items in list. Try -d help for further information.-liveDebug liveness analysis.-vIncrease debug verbosity.-%Debug non-static initializers.-WDebug parse tree after type checking.-fDebug stack frames.-iDebug line number stack.-jDebug runtime-initialized variables.-rDebug generated wrappers.-wDebug type checking.

Compiler Directives

The compiler accepts directives in the form of comments.Each directive must be placed its own line, with only leading spaces and tabsallowed before the comment, and there must be no space between the commentopening and the name of the directive, to distinguish it from a regular comment.Tools unaware of the directive convention or of a particulardirective can skip over a directive like any other comment.

Other than the line directive, which is a historical special case;all other compiler directives are of the form//go:name, indicating that they are defined by the Go toolchain.

Line Directives

Line directives come in several forms:

//line :line//line :line:col//line filename:line//line filename:line:col/*line :line*//*line :line:col*//*line filename:line*//*line filename:line:col*/

In order to be recognized as a line directive, the comment must start with//line or /*line followed by a space, and must contain at least one colon.The //line form must start at the beginning of a line.A line directive specifies the source position for the character immediately followingthe comment as having come from the specified file, line and column:For a //line comment, this is the first character of the next line, andfor a /*line comment this is the character position immediately following the closing */.If no filename is given, the recorded filename is empty if there is also no column number;otherwise it is the most recently recorded filename (actual filename or filename specifiedby previous line directive).If a line directive doesn't specify a column number, the column is "unknown" untilthe next directive and the compiler does not report column numbers for that range.The line directive text is interpreted from the back: First the trailing :ddd is peeledoff from the directive text if ddd is a valid number > 0. Then the second :dddis peeled off the same way if it is valid. Anything before that is considered the filename(possibly including blanks and colons). Invalid line or column values are reported as errors.

Examples:

//line foo.go:10      the filename is foo.go, and the line number is 10 for the next line//line C:foo.go:10    colons are permitted in filenames, here the filename is C:foo.go, and the line is 10//line  a:100 :10     blanks are permitted in filenames, here the filename is " a:100 " (excluding quotes)/*line :10:20*/x      the position of x is in the current file with line number 10 and column number 20/*line foo: 10 */     this comment is recognized as invalid line directive (extra blanks around line number)

Line directives typically appear in machine-generated code, so that compilers and debuggerswill report positions in the original input to the generator.

Function Directives

A function directive applies to the Go function that immediately follows it.

//go:noescape

The //go:noescape directive must be followed by a function declaration withouta body (meaning that the function has an implementation not written in Go).It specifies that the function does not allow any of the pointers passed asarguments to escape into the heap or into the values returned from the function.This information can be used during the compiler's escape analysis of Go codecalling the function.

//go:uintptrescapes

The //go:uintptrescapes directive must be followed by a function declaration.It specifies that the function's uintptr arguments may be pointer values thathave been converted to uintptr and must be on the heap and kept alive for theduration of the call, even though from the types alone it would appear that theobject is no longer needed during the call. The conversion from pointer touintptr must appear in the argument list of any call to this function. Thisdirective is necessary for some low-level system call implementations andshould be avoided otherwise.

//go:noinline

The //go:noinline directive must be followed by a function declaration.It specifies that calls to the function should not be inlined, overridingthe compiler's usual optimization rules. This is typically only neededfor special runtime functions or when debugging the compiler.

//go:norace

The //go:norace directive must be followed by a function declaration.It specifies that the function's memory accesses must be ignored by therace detector. This is most commonly used in low-level code invokedat times when it is unsafe to call into the race detector runtime.

//go:nosplit

The //go:nosplit directive must be followed by a function declaration.It specifies that the function must omit its usual stack overflow check.This is most commonly used by low-level runtime code invokedat times when it is unsafe for the calling goroutine to be preempted.Using this directive outside of low-level runtime code is not safe,because it permits the nosplit function to overwrite the end of stack,leading to memory corruption and arbitrary program failure.

Linkname Directive

//go:linkname localname [importpath.name]

The //go:linkname directive conventionally precedes the var or funcdeclaration named by “localname“, though its position does notchange its effect.This directive determines the object-file symbol used for a Go var orfunc declaration, allowing two Go symbols to alias the sameobject-file symbol, thereby enabling one package to access a symbol inanother package even when this would violate the usual encapsulationof unexported declarations, or even type safety.For that reason, it is only enabled in files that have imported "unsafe".

It may be used in two scenarios. Let's assume that package upperimports package lower, perhaps indirectly. In the first scenario,package lower defines a symbol whose object file name belongs topackage upper. Both packages contain a linkname directive: packagelower uses the two-argument form and package upper uses theone-argument form. In the example below, lower.f is an alias for thefunction upper.g:

package upperimport _ "unsafe"//go:linkname gfunc g()package lowerimport _ "unsafe"//go:linkname f upper.gfunc f() { ... }

The linkname directive in package upper suppresses the usual error fora function that lacks a body. (That check may alternatively besuppressed by including a .s file, even an empty one, in the package.)

In the second scenario, package upper unilaterally creates an aliasfor a symbol in package lower. In the example below, upper.g is an aliasfor the function lower.f.

package upperimport _ "unsafe"//go:linkname g lower.ffunc g()package lowerfunc f() { ... }

The declaration of lower.f may also have a linkname directive with asingle argument, f. This is optional, but helps alert the reader thatthe function is accessed from outside the package.

WebAssembly Directives

//go:wasmimport importmodule importname

The //go:wasmimport directive is wasm-only and must be followed by afunction declaration with no body.It specifies that the function is provided by a wasm module identifiedby “importmodule” and “importname”. For example,

//go:wasmimport a_module ffunc g()

causes g to refer to the WebAssembly function f from module a_module.

//go:wasmexport exportname

The //go:wasmexport directive is wasm-only and must be followed by afunction definition.It specifies that the function is exported to the wasm host as “exportname”.For example,

//go:wasmexport hfunc hWasm() { ... }

make Go function hWasm available outside this WebAssembly module as h.

For both go:wasmimport and go:wasmexport,the types of parameters and return values to the Go function are translated toWasm according to the following table:

Go types        Wasm typesbool            i32int32, uint32   i32int64, uint64   i64float32         f32float64         f64unsafe.Pointer  i32pointer         i32 (more restrictions below)string          (i32, i32) (only permitted as a parameters, not a result)

Any other parameter types are disallowed by the compiler.

For a pointer type, its element type must be a bool, int8, uint8, int16, uint16,int32, uint32, int64, uint64, float32, float64, an array whose element type isa permitted pointer element type, or a struct, which, if non-empty, embedsstructs.HostLayout, and contains only fields whose types are permitted pointerelement types.

Source Files

View all Source files

Directories

PathSynopsis
internal
compare
Package compare contains code for generating comparison routines for structs, strings and interfaces.
Package compare contains code for generating comparison routines for structs, strings and interfaces.
deadlocals
The deadlocals pass removes assignments to unused local variables.
The deadlocals pass removes assignments to unused local variables.
devirtualize
Package devirtualize implements two "devirtualization" optimization passes:
Package devirtualize implements two "devirtualization" optimization passes:
importer
package importer implements package reading for gc-generated object files.
package importer implements package reading for gc-generated object files.
inline/interleaved
Package interleaved implements the interleaved devirtualization and inlining pass.
Package interleaved implements the interleaved devirtualization and inlining pass.
loopvar
Package loopvar applies the proper variable capture, according to experiment, flags, language version, etc.
Package loopvar applies the proper variable capture, according to experiment, flags, language version, etc.
pgoir
Package pgoir associates a PGO profile with the IR of the current package compilation.
Package pgoir associates a PGO profile with the IR of the current package compilation.
rangefunc
Package rangefunc rewrites range-over-func to code that doesn't use range-over-funcs.
Package rangefunc rewrites range-over-func to code that doesn't use range-over-funcs.
rttype
Package rttype allows the compiler to share type information with the runtime.
Package rttype allows the compiler to share type information with the runtime.
types2
Package types2 declares the data types and implements the algorithms for type-checking of Go packages.
Package types2 declares the data types and implements the algorithms for type-checking of Go packages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp