go tool compile, compiles a single Go package comprising the files named on the command line. It writes object files that can be combined into packages or passed to the linker.
Overview
The compiler is typically invoked indirectly through thego build command, but can be used directly for specialized build processes or when debugging compilation issues.
Most users should use
go build instead of calling the compiler directly. Direct compiler invocation is primarily for advanced use cases and build system integration.Usage
Basic Flags
Output Control
Write object to file (default:
file.o or with -pack, file.a)Write a package (archive) file rather than an object file
Print assembly listing to standard output. Use
-S -S to include data sections.Path and Import Flags
Set relative path for local imports
Search for imported packages in specified directories (can be repeated)
Set expected package import path for the code being compiled
Optimization Flags
Disable optimizations. Useful for debugging.
Disable inlining. Combining with
-N provides better debugging experience.Print optimization decisions. Use multiple times for more detail.
Common Workflows
Viewing Assembly Output
Analyzing Optimizations
Advanced Flags
Debug and Analysis
Compile with race detector enabled
Insert calls to C/C++ address sanitizer (Linux only)
Insert calls to C/C++ memory sanitizer (Linux only)
Build Configuration
Record id as the build id in the export metadata
Read import configuration from file. Used to specify import resolution.
Read go:embed configuration from file. Required if any
//go:embed directives are used.Language Version
Set language version to compile, as in
-lang=go1.21Specify required go tool version of the runtime
DWARF Debug Information
Generate DWARF symbols for debugging
Add location lists to DWARF in optimized mode
Generate DWARF inline info records (default: 2)
Profiling Flags
Compiler Debugging Flags
Print debug information about items in list
Debug liveness analysis
Increase debug verbosity
Halt with a stack trace at the first error detected
Remove the limit on the number of errors reported (default limit is 10)
Examples
Basic Compilation
Cross-Compilation
Debugging Compilation
Using with go build
Pass compiler flags throughgo build using -gcflags:
Compiler Directives
The compiler accepts directives in the form of comments:Function Directives
Line Directives
WebAssembly Directives
Compiler Internals
Compilation Phases
Performance Tuning
Compilation Speed
Binary Size
Troubleshooting
Compilation errors with type checking
Compilation errors with type checking
Use
-e flag to see all errors at once:Debugging optimization issues
Debugging optimization issues
Disable optimizations and check if issue persists:
Understanding why code doesn't inline
Understanding why code doesn't inline
Check inlining decisions:
See Also
Building Programs
Using go build command
go Command
Overview of go command