1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 Cgo enables the creation of Go packages that call C code.
9 Using cgo with the go command
11 To use cgo write normal Go code that imports a pseudo-package "C".
12 The Go code can then refer to types such as C.size_t, variables such
13 as C.stdout, or functions such as C.putchar.
15 If the import of "C" is immediately preceded by a comment, that
16 comment, called the preamble, is used as a header when compiling
17 the C parts of the package. For example:
23 The preamble may contain any C code, including function and variable
24 declarations and definitions. These may then be referred to from Go
25 code as though they were defined in the package "C". All names
26 declared in the preamble may be used, even if they start with a
27 lower-case letter. Exception: static variables in the preamble may
28 not be referenced from Go code; static functions are permitted.
30 See $GOROOT/misc/cgo/stdio and $GOROOT/misc/cgo/gmp for examples. See
31 "C? Go? Cgo!" for an introduction to using cgo:
32 https://golang.org/doc/articles/c_go_cgo.html.
34 CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS may be defined with pseudo #cgo
35 directives within these comments to tweak the behavior of the C or C++
36 compiler. Values defined in multiple directives are concatenated
37 together. The directive can include a list of build constraints limiting its
38 effect to systems satisfying one of the constraints
39 (see https://golang.org/pkg/go/build/#hdr-Build_Constraints for details about the constraint syntax).
42 // #cgo CFLAGS: -DPNG_DEBUG=1
43 // #cgo amd64 386 CFLAGS: -DX86=1
44 // #cgo LDFLAGS: -lpng
48 Alternatively, CPPFLAGS and LDFLAGS may be obtained via the pkg-config
49 tool using a '#cgo pkg-config:' directive followed by the package names.
52 // #cgo pkg-config: png cairo
56 When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS and
57 CGO_LDFLAGS environment variables are added to the flags derived from
58 these directives. Package-specific flags should be set using the
59 directives, not the environment variables, so that builds work in
60 unmodified environments.
62 All the cgo CPPFLAGS and CFLAGS directives in a package are concatenated and
63 used to compile C files in that package. All the CPPFLAGS and CXXFLAGS
64 directives in a package are concatenated and used to compile C++ files in that
65 package. All the LDFLAGS directives in any package in the program are
66 concatenated and used at link time. All the pkg-config directives are
67 concatenated and sent to pkg-config simultaneously to add to each appropriate
68 set of command-line flags.
70 When the cgo directives are parsed, any occurrence of the string ${SRCDIR}
71 will be replaced by the absolute path to the directory containing the source
72 file. This allows pre-compiled static libraries to be included in the package
73 directory and linked properly.
74 For example if package foo is in the directory /go/src/foo:
76 // #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo
80 // #cgo LDFLAGS: -L/go/src/foo/libs -lfoo
82 When the Go tool sees that one or more Go files use the special import
83 "C", it will look for other non-Go files in the directory and compile
84 them as part of the Go package. Any .c, .s, or .S files will be
85 compiled with the C compiler. Any .cc, .cpp, or .cxx files will be
86 compiled with the C++ compiler. Any .h, .hh, .hpp, or .hxx files will
87 not be compiled separately, but, if these header files are changed,
88 the C and C++ files will be recompiled. The default C and C++
89 compilers may be changed by the CC and CXX environment variables,
90 respectively; those environment variables may include command line
93 The cgo tool is enabled by default for native builds on systems where
94 it is expected to work. It is disabled by default when
95 cross-compiling. You can control this by setting the CGO_ENABLED
96 environment variable when running the go tool: set it to 1 to enable
97 the use of cgo, and to 0 to disable it. The go tool will set the
98 build constraint "cgo" if cgo is enabled.
100 When cross-compiling, you must specify a C cross-compiler for cgo to
101 use. You can do this by setting the CC_FOR_TARGET environment
102 variable when building the toolchain using make.bash, or by setting
103 the CC environment variable any time you run the go tool. The
104 CXX_FOR_TARGET and CXX environment variables work in a similar way for
109 Within the Go file, C's struct field names that are keywords in Go
110 can be accessed by prefixing them with an underscore: if x points at a C
111 struct with a field named "type", x._type accesses the field.
112 C struct fields that cannot be expressed in Go, such as bit fields
113 or misaligned data, are omitted in the Go struct, replaced by
114 appropriate padding to reach the next field or the end of the struct.
116 The standard C numeric types are available under the names
117 C.char, C.schar (signed char), C.uchar (unsigned char),
118 C.short, C.ushort (unsigned short), C.int, C.uint (unsigned int),
119 C.long, C.ulong (unsigned long), C.longlong (long long),
120 C.ulonglong (unsigned long long), C.float, C.double.
121 The C type void* is represented by Go's unsafe.Pointer.
123 To access a struct, union, or enum type directly, prefix it with
124 struct_, union_, or enum_, as in C.struct_stat.
126 As Go doesn't have support for C's union type in the general case,
127 C's union types are represented as a Go byte array with the same length.
129 Go structs cannot embed fields with C types.
131 Cgo translates C types into equivalent unexported Go types.
132 Because the translations are unexported, a Go package should not
133 expose C types in its exported API: a C type used in one Go package
134 is different from the same C type used in another.
136 Any C function (even void functions) may be called in a multiple
137 assignment context to retrieve both the return value (if any) and the
138 C errno variable as an error (use _ to skip the result value if the
139 function returns void). For example:
142 _, err := C.voidFunc()
144 Calling C function pointers is currently not supported, however you can
145 declare Go variables which hold C function pointers and pass them
146 back and forth between Go and C. C code may call function pointers
147 received from Go. For example:
151 // typedef int (*intFunc) ();
154 // bridge_int_func(intFunc f)
167 f := C.intFunc(C.fortytwo)
168 fmt.Println(int(C.bridge_int_func(f)))
172 In C, a function argument written as a fixed size array
173 actually requires a pointer to the first element of the array.
174 C compilers are aware of this calling convention and adjust
175 the call accordingly, but Go cannot. In Go, you must pass
176 the pointer to the first element explicitly: C.f(&C.x[0]).
178 A few special functions convert between Go and C types
179 by making copies of the data. In pseudo-Go definitions:
181 // Go string to C string
182 // The C string is allocated in the C heap using malloc.
183 // It is the caller's responsibility to arrange for it to be
184 // freed, such as by calling C.free (be sure to include stdlib.h
185 // if C.free is needed).
186 func C.CString(string) *C.char
188 // C string to Go string
189 func C.GoString(*C.char) string
191 // C string, length to Go string
192 func C.GoStringN(*C.char, C.int) string
194 // C pointer, length to Go []byte
195 func C.GoBytes(unsafe.Pointer, C.int) []byte
199 Go functions can be exported for use by C code in the following way:
202 func MyFunction(arg1, arg2 int, arg3 string) int64 {...}
205 func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
207 They will be available in the C code as:
209 extern int64 MyFunction(int arg1, int arg2, GoString arg3);
210 extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);
212 found in the _cgo_export.h generated header, after any preambles
213 copied from the cgo input files. Functions with multiple
214 return values are mapped to functions returning a struct.
215 Not all Go types can be mapped to C types in a useful way.
217 Using //export in a file places a restriction on the preamble:
218 since it is copied into two different C output files, it must not
219 contain any definitions, only declarations. If a file contains both
220 definitions and declarations, then the two output files will produce
221 duplicate symbols and the linker will fail. To avoid this, definitions
222 must be placed in preambles in other files, or in C source files.
227 go tool cgo [cgo options] [-- compiler options] gofiles...
229 Cgo transforms the specified input Go source files into several output
230 Go and C source files.
232 The compiler options are passed through uninterpreted when
233 invoking the C compiler to compile the C parts of the package.
235 The following options are available when running cgo directly:
238 Write list of symbols imported by file. Write to
239 -dynout argument or to standard output. Used by go
240 build when building a cgo package.
242 Write -dynimport output to file.
244 Set Go package for -dynimport output.
246 Write dynamic linker as part of -dynimport output.
248 Write out input file in Go syntax replacing C package
249 names with real values. Used to generate files in the
250 syscall package when bootstrapping a new target.
252 Put all generated files in directory.
254 The import path for the Go package. Optional; used for
255 nicer comments in the generated files.
257 If there are any exported functions, write the
258 generated export declarations to file.
259 C code can #include this to see the declarations.
261 Generate output for the gccgo compiler rather than the
264 The -fgo-prefix option to be used with gccgo.
266 The -fgo-pkgpath option to be used with gccgo.
268 If set (which it is by default) import runtime/cgo in
271 If set (which it is by default) import syscall in
274 Debugging option. Print #defines.
276 Debugging option. Trace C compiler execution and output.
281 Implementation details.
283 Cgo provides a way for Go programs to call C code linked into the same
284 address space. This comment explains the operation of cgo.
286 Cgo reads a set of Go source files and looks for statements saying
287 import "C". If the import has a doc comment, that comment is
288 taken as literal C code to be used as a preamble to any C code
289 generated by cgo. A typical preamble #includes necessary definitions:
291 // #include <stdio.h>
294 For more details about the usage of cgo, see the documentation
295 comment at the top of this file.
299 Cgo scans the Go source files that import "C" for uses of that
300 package, such as C.puts. It collects all such identifiers. The next
301 step is to determine each kind of name. In C.xxx the xxx might refer
302 to a type, a function, a constant, or a global variable. Cgo must
305 The obvious thing for cgo to do is to process the preamble, expanding
306 #includes and processing the corresponding C code. That would require
307 a full C parser and type checker that was also aware of any extensions
308 known to the system compiler (for example, all the GNU C extensions) as
309 well as the system-specific header locations and system-specific
310 pre-#defined macros. This is certainly possible to do, but it is an
311 enormous amount of work.
313 Cgo takes a different approach. It determines the meaning of C
314 identifiers not by parsing C code but by feeding carefully constructed
315 programs into the system C compiler and interpreting the generated
316 error messages, debug information, and object files. In practice,
317 parsing these is significantly less work and more robust than parsing
320 Cgo first invokes gcc -E -dM on the preamble, in order to find out
321 about simple #defines for constants and the like. These are recorded
324 Next, cgo needs to identify the kinds for each identifier. For the
325 identifiers C.foo and C.bar, cgo generates this C program:
328 #line 1 "not-declared"
329 void __cgo_f_xxx_1(void) { __typeof__(foo) *__cgo_undefined__; }
331 void __cgo_f_xxx_2(void) { foo *__cgo_undefined__; }
333 void __cgo_f_xxx_3(void) { enum { __cgo_undefined__ = (foo)*1 }; }
334 #line 2 "not-declared"
335 void __cgo_f_xxx_1(void) { __typeof__(bar) *__cgo_undefined__; }
337 void __cgo_f_xxx_2(void) { bar *__cgo_undefined__; }
339 void __cgo_f_xxx_3(void) { enum { __cgo_undefined__ = (bar)*1 }; }
341 This program will not compile, but cgo can use the presence or absence
342 of an error message on a given line to deduce the information it
343 needs. The program is syntactically valid regardless of whether each
344 name is a type or an ordinary identifier, so there will be no syntax
345 errors that might stop parsing early.
347 An error on not-declared:1 indicates that foo is undeclared.
348 An error on not-type:1 indicates that foo is not a type (if declared at all, it is an identifier).
349 An error on not-const:1 indicates that foo is not an integer constant.
351 The line number specifies the name involved. In the example, 1 is foo and 2 is bar.
353 Next, cgo must learn the details of each type, variable, function, or
354 constant. It can do this by reading object files. If cgo has decided
355 that t1 is a type, v2 and v3 are variables or functions, and c4, c5,
356 and c6 are constants, it generates:
359 __typeof__(t1) *__cgo__1;
360 __typeof__(v2) *__cgo__2;
361 __typeof__(v3) *__cgo__3;
362 __typeof__(c4) *__cgo__4;
363 enum { __cgo_enum__4 = c4 };
364 __typeof__(c5) *__cgo__5;
365 enum { __cgo_enum__5 = c5 };
366 __typeof__(c6) *__cgo__6;
367 enum { __cgo_enum__6 = c6 };
369 long long __cgo_debug_data[] = {
379 and again invokes the system C compiler, to produce an object file
380 containing debug information. Cgo parses the DWARF debug information
381 for __cgo__N to learn the type of each identifier. (The types also
382 distinguish functions from global variables.) If using a standard gcc,
383 cgo can parse the DWARF debug information for the __cgo_enum__N to
384 learn the identifier's value. The LLVM-based gcc on OS X emits
385 incomplete DWARF information for enums; in that case cgo reads the
386 constant values from the __cgo_debug_data from the object file's data
389 At this point cgo knows the meaning of each C.xxx well enough to start
390 the translation process.
394 [The rest of this comment refers to 6g, the Go compiler that is part
395 of the amd64 port of the gc Go toolchain. Everything here applies to
396 another architecture's compilers as well.]
398 Given the input Go files x.go and y.go, cgo generates these source
403 _cgo_gotypes.go # for 6g
404 _cgo_import.go # for 6g (if -dynout _cgo_import.go)
407 _cgo_defun.c # for gcc (if -gccgo)
408 _cgo_export.c # for gcc
409 _cgo_export.h # for gcc
410 _cgo_main.c # for gcc
411 _cgo_flags # for alternative build tools
413 The file x.cgo1.go is a copy of x.go with the import "C" removed and
414 references to C.xxx replaced with names like _Cfunc_xxx or _Ctype_xxx.
415 The definitions of those identifiers, written as Go functions, types,
416 or variables, are provided in _cgo_gotypes.go.
418 Here is a _cgo_gotypes.go containing definitions for needed C types:
420 type _Ctype_char int8
421 type _Ctype_int int32
422 type _Ctype_void [0]byte
424 The _cgo_gotypes.go file also contains the definitions of the
425 functions. They all have similar bodies that invoke runtime·cgocall
426 to make a switch from the Go runtime world to the system C (GCC-based)
429 For example, here is the definition of _Cfunc_puts:
431 //go:cgo_import_static _cgo_be59f0f25121_Cfunc_puts
432 //go:linkname __cgofn__cgo_be59f0f25121_Cfunc_puts _cgo_be59f0f25121_Cfunc_puts
433 var __cgofn__cgo_be59f0f25121_Cfunc_puts byte
434 var _cgo_be59f0f25121_Cfunc_puts = unsafe.Pointer(&__cgofn__cgo_be59f0f25121_Cfunc_puts)
436 func _Cfunc_puts(p0 *_Ctype_char) (r1 _Ctype_int) {
437 _cgo_runtime_cgocall(_cgo_be59f0f25121_Cfunc_puts, uintptr(unsafe.Pointer(&p0)))
441 The hexadecimal number is a hash of cgo's input, chosen to be
442 deterministic yet unlikely to collide with other uses. The actual
443 function _cgo_be59f0f25121_Cfunc_puts is implemented in a C source
444 file compiled by gcc, the file x.cgo2.c:
447 _cgo_be59f0f25121_Cfunc_puts(void *v)
449 _cgo_wait_runtime_init_done();
454 } __attribute__((__packed__, __gcc_struct__)) *a = v;
455 a->r = puts((void*)a->p0);
458 It waits for Go runtime to be initialized (required for shared libraries),
459 extracts the arguments from the pointer to _Cfunc_puts's argument
460 frame, invokes the system C function (in this case, puts), stores the
461 result in the frame, and returns.
465 Once the _cgo_export.c and *.cgo2.c files have been compiled with gcc,
466 they need to be linked into the final binary, along with the libraries
467 they might depend on (in the case of puts, stdio). 6l has been
468 extended to understand basic ELF files, but it does not understand ELF
469 in the full complexity that modern C libraries embrace, so it cannot
470 in general generate direct references to the system libraries.
472 Instead, the build process generates an object file using dynamic
473 linkage to the desired libraries. The main function is provided by
476 int main() { return 0; }
477 void crosscall2(void(*fn)(void*, int), void *a, int c) { }
478 void _cgo_wait_runtime_init_done() { }
479 void _cgo_allocate(void *a, int c) { }
480 void _cgo_panic(void *a, int c) { }
482 The extra functions here are stubs to satisfy the references in the C
483 code generated for gcc. The build process links this stub, along with
484 _cgo_export.c and *.cgo2.c, into a dynamic executable and then lets
485 cgo examine the executable. Cgo records the list of shared library
486 references and resolved names and writes them into a new file
487 _cgo_import.go, which looks like:
489 //go:cgo_dynamic_linker "/lib64/ld-linux-x86-64.so.2"
490 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6"
491 //go:cgo_import_dynamic __libc_start_main __libc_start_main#GLIBC_2.2.5 "libc.so.6"
492 //go:cgo_import_dynamic stdout stdout#GLIBC_2.2.5 "libc.so.6"
493 //go:cgo_import_dynamic fflush fflush#GLIBC_2.2.5 "libc.so.6"
494 //go:cgo_import_dynamic _ _ "libpthread.so.0"
495 //go:cgo_import_dynamic _ _ "libc.so.6"
497 In the end, the compiled Go package, which will eventually be
498 presented to 6l as part of a larger program, contains:
500 _go_.6 # 6g-compiled object for _cgo_gotypes.go, _cgo_import.go, *.cgo1.go
501 _all.o # gcc-compiled object for _cgo_export.c, *.cgo2.c
503 The final program will be a dynamic executable, so that 6l can avoid
504 needing to process arbitrary .o files. It only needs to process the .o
505 files generated from C files that cgo writes, and those are much more
506 limited in the ELF or other features that they use.
508 In essence, the _cgo_import.6 file includes the extra linking
509 directives that 6l is not sophisticated enough to derive from _all.o
510 on its own. Similarly, the _all.o uses dynamic references to real
511 system object code because 6l is not sophisticated enough to process
514 The main benefits of this system are that 6l remains relatively simple
515 (it does not need to implement a complete ELF and Mach-O linker) and
516 that gcc is not needed after the package is compiled. For example,
517 package net uses cgo for access to name resolution functions provided
518 by libc. Although gcc is needed to compile package net, gcc is not
519 needed to link programs that import package net.
523 When using cgo, Go must not assume that it owns all details of the
524 process. In particular it needs to coordinate with C in the use of
525 threads and thread-local storage. The runtime package declares a few
530 _cgo_init unsafe.Pointer
531 _cgo_thread_start unsafe.Pointer
534 Any package using cgo imports "runtime/cgo", which provides
535 initializations for these variables. It sets iscgo to true, _cgo_init
536 to a gcc-compiled function that can be called early during program
537 startup, and _cgo_thread_start to a gcc-compiled function that can be
538 used to create a new thread, in place of the runtime's usual direct
541 Internal and External Linking
543 The text above describes "internal" linking, in which 6l parses and
544 links host object files (ELF, Mach-O, PE, and so on) into the final
545 executable itself. Keeping 6l simple means we cannot possibly
546 implement the full semantics of the host linker, so the kinds of
547 objects that can be linked directly into the binary is limited (other
548 code can only be used as a dynamic library). On the other hand, when
549 using internal linking, 6l can generate Go binaries by itself.
551 In order to allow linking arbitrary object files without requiring
552 dynamic libraries, cgo supports an "external" linking mode too. In
553 external linking mode, 6l does not process any host object files.
554 Instead, it collects all the Go code and writes a single go.o object
555 file containing it. Then it invokes the host linker (usually gcc) to
556 combine the go.o object file and any supporting non-Go code into a
557 final executable. External linking avoids the dynamic library
558 requirement but introduces a requirement that the host linker be
559 present to create such a binary.
561 Most builds both compile source code and invoke the linker to create a
562 binary. When cgo is involved, the compile step already requires gcc, so
563 it is not problematic for the link step to require gcc too.
565 An important exception is builds using a pre-compiled copy of the
566 standard library. In particular, package net uses cgo on most systems,
567 and we want to preserve the ability to compile pure Go code that
568 imports net without requiring gcc to be present at link time. (In this
569 case, the dynamic library requirement is less significant, because the
570 only library involved is libc.so, which can usually be assumed
573 This conflict between functionality and the gcc requirement means we
574 must support both internal and external linking, depending on the
575 circumstances: if net is the only cgo-using package, then internal
576 linking is probably fine, but if other packages are involved, so that there
577 are dependencies on libraries beyond libc, external linking is likely
578 to work better. The compilation of a package records the relevant
579 information to support both linking modes, leaving the decision
580 to be made when linking the final binary.
584 In either linking mode, package-specific directives must be passed
585 through to 6l. These are communicated by writing //go: directives in a
586 Go source file compiled by 6g. The directives are copied into the .6
587 object file and then processed by the linker.
591 //go:cgo_import_dynamic <local> [<remote> ["<library>"]]
593 In internal linking mode, allow an unresolved reference to
594 <local>, assuming it will be resolved by a dynamic library
595 symbol. The optional <remote> specifies the symbol's name and
596 possibly version in the dynamic library, and the optional "<library>"
597 names the specific library where the symbol should be found.
599 In the <remote>, # or @ can be used to introduce a symbol version.
602 //go:cgo_import_dynamic puts
603 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5
604 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6"
606 A side effect of the cgo_import_dynamic directive with a
607 library is to make the final binary depend on that dynamic
608 library. To get the dependency without importing any specific
609 symbols, use _ for local and remote.
612 //go:cgo_import_dynamic _ _ "libc.so.6"
614 For compatibility with current versions of SWIG,
615 #pragma dynimport is an alias for //go:cgo_import_dynamic.
617 //go:cgo_dynamic_linker "<path>"
619 In internal linking mode, use "<path>" as the dynamic linker
620 in the final binary. This directive is only needed from one
621 package when constructing a binary; by convention it is
622 supplied by runtime/cgo.
625 //go:cgo_dynamic_linker "/lib/ld-linux.so.2"
627 //go:cgo_export_dynamic <local> <remote>
629 In internal linking mode, put the Go symbol
630 named <local> into the program's exported symbol table as
631 <remote>, so that C code can refer to it by that name. This
632 mechanism makes it possible for C code to call back into Go or
635 For compatibility with current versions of SWIG,
636 #pragma dynexport is an alias for //go:cgo_export_dynamic.
638 //go:cgo_import_static <local>
640 In external linking mode, allow unresolved references to
641 <local> in the go.o object file prepared for the host linker,
642 under the assumption that <local> will be supplied by the
643 other object files that will be linked with go.o.
646 //go:cgo_import_static puts_wrapper
648 //go:cgo_export_static <local> <remote>
650 In external linking mode, put the Go symbol
651 named <local> into the program's exported symbol table as
652 <remote>, so that C code can refer to it by that name. This
653 mechanism makes it possible for C code to call back into Go or
656 //go:cgo_ldflag "<arg>"
658 In external linking mode, invoke the host linker (usually gcc)
659 with "<arg>" as a command-line argument following the .o files.
660 Note that the arguments are for "gcc", not "ld".
663 //go:cgo_ldflag "-lpthread"
664 //go:cgo_ldflag "-L/usr/local/sqlite3/lib"
666 A package compiled with cgo will include directives for both
667 internal and external linking; the linker will select the appropriate
668 subset for the chosen linking mode.
672 As a simple example, consider a package that uses cgo to call C.sin.
673 The following code will be generated by cgo:
677 //go:cgo_ldflag "-lm"
679 type _Ctype_double float64
681 //go:cgo_import_static _cgo_gcc_Cfunc_sin
682 //go:linkname __cgo_gcc_Cfunc_sin _cgo_gcc_Cfunc_sin
683 var __cgo_gcc_Cfunc_sin byte
684 var _cgo_gcc_Cfunc_sin = unsafe.Pointer(&__cgo_gcc_Cfunc_sin)
686 func _Cfunc_sin(p0 _Ctype_double) (r1 _Ctype_double) {
687 _cgo_runtime_cgocall(_cgo_gcc_Cfunc_sin, uintptr(unsafe.Pointer(&p0)))
691 // compiled by gcc, into foo.cgo2.o
694 _cgo_gcc_Cfunc_sin(void *v)
699 } __attribute__((__packed__)) *a = v;
703 What happens at link time depends on whether the final binary is linked
704 using the internal or external mode. If other packages are compiled in
705 "external only" mode, then the final link will be an external one.
706 Otherwise the link will be an internal one.
708 The linking directives are used according to the kind of final link
711 In internal mode, 6l itself processes all the host object files, in
712 particular foo.cgo2.o. To do so, it uses the cgo_import_dynamic and
713 cgo_dynamic_linker directives to learn that the otherwise undefined
714 reference to sin in foo.cgo2.o should be rewritten to refer to the
715 symbol sin with version GLIBC_2.2.5 from the dynamic library
716 "libm.so.6", and the binary should request "/lib/ld-linux.so.2" as its
717 runtime dynamic linker.
719 In external mode, 6l does not process any host object files, in
720 particular foo.cgo2.o. It links together the 6g-generated object
721 files, along with any other Go code, into a go.o file. While doing
722 that, 6l will discover that there is no definition for
723 _cgo_gcc_Cfunc_sin, referred to by the 6g-compiled source file. This
724 is okay, because 6l also processes the cgo_import_static directive and
725 knows that _cgo_gcc_Cfunc_sin is expected to be supplied by a host
726 object file, so 6l does not treat the missing symbol as an error when
727 creating go.o. Indeed, the definition for _cgo_gcc_Cfunc_sin will be
728 provided to the host linker by foo2.cgo.o, which in turn will need the
729 symbol 'sin'. 6l also processes the cgo_ldflag directives, so that it
730 knows that the eventual host link command must include the -lm
731 argument, so that the host linker will be able to find 'sin' in the
734 6l Command Line Interface
736 The go command and any other Go-aware build systems invoke 6l
737 to link a collection of packages into a single binary. By default, 6l will
738 present the same interface it does today:
742 produces a file named 6.out, even if 6l does so by invoking the host
743 linker in external linking mode.
745 By default, 6l will decide the linking mode as follows: if the only
746 packages using cgo are those on a whitelist of standard library
747 packages (net, os/user, runtime/cgo), 6l will use internal linking
748 mode. Otherwise, there are non-standard cgo packages involved, and 6l
749 will use external linking mode. The first rule means that a build of
750 the godoc binary, which uses net but no other cgo, can run without
751 needing gcc available. The second rule means that a build of a
752 cgo-wrapped library like sqlite3 can generate a standalone executable
753 instead of needing to refer to a dynamic library. The specific choice
754 can be overridden using a command line flag: 6l -linkmode=internal or
755 6l -linkmode=external.
757 In an external link, 6l will create a temporary directory, write any
758 host object files found in package archives to that directory (renamed
759 to avoid conflicts), write the go.o file to that directory, and invoke
760 the host linker. The default value for the host linker is $CC, split
761 into fields, or else "gcc". The specific host linker command line can
762 be overridden using command line flags: 6l -extld=clang
763 -extldflags='-ggdb -O3'. If any package in a build includes a .cc or
764 other file compiled by the C++ compiler, the go tool will use the
765 -extld option to set the host linker to the C++ compiler.
767 These defaults mean that Go-aware build systems can ignore the linking
768 changes and keep running plain '6l' and get reasonable results, but
769 they can also control the linking details if desired.