b2a5428f3f4dfac7c42356014e3fd0cc7a85fa4a
[platform/upstream/gcc.git] / libgo / go / cmd / cgo / doc.go
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.
4
5 /*
6
7 Cgo enables the creation of Go packages that call C code.
8
9 Using cgo with the go command
10
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.
14
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:
18
19         // #include <stdio.h>
20         // #include <errno.h>
21         import "C"
22
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.
29
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.
33
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).
40 For example:
41
42         // #cgo CFLAGS: -DPNG_DEBUG=1
43         // #cgo amd64 386 CFLAGS: -DX86=1
44         // #cgo LDFLAGS: -lpng
45         // #include <png.h>
46         import "C"
47
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.
50 For example:
51
52         // #cgo pkg-config: png cairo
53         // #include <png.h>
54         import "C"
55
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.
61
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.
69
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:
75
76        // #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo
77
78 Will be expanded to:
79
80        // #cgo LDFLAGS: -L/go/src/foo/libs -lfoo
81
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
91 options.
92
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.
99
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
105 C++ code.
106
107 Go references to C
108
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.
115
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.
122
123 To access a struct, union, or enum type directly, prefix it with
124 struct_, union_, or enum_, as in C.struct_stat.
125
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.
128
129 Go structs cannot embed fields with C types.
130
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.
135
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:
140
141         n, err := C.sqrt(-1)
142         _, err := C.voidFunc()
143
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:
148
149         package main
150
151         // typedef int (*intFunc) ();
152         //
153         // int
154         // bridge_int_func(intFunc f)
155         // {
156         //              return f();
157         // }
158         //
159         // int fortytwo()
160         // {
161         //          return 42;
162         // }
163         import "C"
164         import "fmt"
165
166         func main() {
167                 f := C.intFunc(C.fortytwo)
168                 fmt.Println(int(C.bridge_int_func(f)))
169                 // Output: 42
170         }
171
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]).
177
178 A few special functions convert between Go and C types
179 by making copies of the data.  In pseudo-Go definitions:
180
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
187
188         // C string to Go string
189         func C.GoString(*C.char) string
190
191         // C string, length to Go string
192         func C.GoStringN(*C.char, C.int) string
193
194         // C pointer, length to Go []byte
195         func C.GoBytes(unsafe.Pointer, C.int) []byte
196
197 C references to Go
198
199 Go functions can be exported for use by C code in the following way:
200
201         //export MyFunction
202         func MyFunction(arg1, arg2 int, arg3 string) int64 {...}
203
204         //export MyFunction2
205         func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
206
207 They will be available in the C code as:
208
209         extern int64 MyFunction(int arg1, int arg2, GoString arg3);
210         extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);
211
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.
216
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.
223
224 Using cgo directly
225
226 Usage:
227         go tool cgo [cgo options] [-- compiler options] gofiles...
228
229 Cgo transforms the specified input Go source files into several output
230 Go and C source files.
231
232 The compiler options are passed through uninterpreted when
233 invoking the C compiler to compile the C parts of the package.
234
235 The following options are available when running cgo directly:
236
237         -dynimport file
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.
241         -dynout file
242                 Write -dynimport output to file.
243         -dynpackage package
244                 Set Go package for -dynimport output.
245         -dynlinker
246                 Write dynamic linker as part of -dynimport output.
247         -godefs
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.
251         -objdir directory
252                 Put all generated files in directory.
253         -importpath string
254                 The import path for the Go package. Optional; used for
255                 nicer comments in the generated files.
256         -exportheader file
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.
260         -gccgo
261                 Generate output for the gccgo compiler rather than the
262                 gc compiler.
263         -gccgoprefix prefix
264                 The -fgo-prefix option to be used with gccgo.
265         -gccgopkgpath path
266                 The -fgo-pkgpath option to be used with gccgo.
267         -import_runtime_cgo
268                 If set (which it is by default) import runtime/cgo in
269                 generated output.
270         -import_syscall
271                 If set (which it is by default) import syscall in
272                 generated output.
273         -debug-define
274                 Debugging option. Print #defines.
275         -debug-gcc
276                 Debugging option. Trace C compiler execution and output.
277 */
278 package main
279
280 /*
281 Implementation details.
282
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.
285
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:
290
291         // #include <stdio.h>
292         import "C"
293
294 For more details about the usage of cgo, see the documentation
295 comment at the top of this file.
296
297 Understanding C
298
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
303 decide which.
304
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.
312
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
318 C source.
319
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
322 for later use.
323
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:
326
327         <preamble>
328         #line 1 "not-declared"
329         void __cgo_f_xxx_1(void) { __typeof__(foo) *__cgo_undefined__; }
330         #line 1 "not-type"
331         void __cgo_f_xxx_2(void) { foo *__cgo_undefined__; }
332         #line 1 "not-const"
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__; }
336         #line 2 "not-type"
337         void __cgo_f_xxx_2(void) { bar *__cgo_undefined__; }
338         #line 2 "not-const"
339         void __cgo_f_xxx_3(void) { enum { __cgo_undefined__ = (bar)*1 }; }
340
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.
346
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.
350
351 The line number specifies the name involved. In the example, 1 is foo and 2 is bar.
352
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:
357
358         <preamble>
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 };
368
369         long long __cgo_debug_data[] = {
370                 0, // t1
371                 0, // v2
372                 0, // v3
373                 c4,
374                 c5,
375                 c6,
376                 1
377         };
378
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
387 segment.
388
389 At this point cgo knows the meaning of each C.xxx well enough to start
390 the translation process.
391
392 Translating Go
393
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.]
397
398 Given the input Go files x.go and y.go, cgo generates these source
399 files:
400
401         x.cgo1.go       # for 6g
402         y.cgo1.go       # for 6g
403         _cgo_gotypes.go # for 6g
404         _cgo_import.go  # for 6g (if -dynout _cgo_import.go)
405         x.cgo2.c        # for gcc
406         y.cgo2.c        # for gcc
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
412
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.
417
418 Here is a _cgo_gotypes.go containing definitions for needed C types:
419
420         type _Ctype_char int8
421         type _Ctype_int int32
422         type _Ctype_void [0]byte
423
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)
427 world.
428
429 For example, here is the definition of _Cfunc_puts:
430
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)
435
436         func _Cfunc_puts(p0 *_Ctype_char) (r1 _Ctype_int) {
437                 _cgo_runtime_cgocall(_cgo_be59f0f25121_Cfunc_puts, uintptr(unsafe.Pointer(&p0)))
438                 return
439         }
440
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:
445
446         void
447         _cgo_be59f0f25121_Cfunc_puts(void *v)
448         {
449                 _cgo_wait_runtime_init_done();
450                 struct {
451                         char* p0;
452                         int r;
453                         char __pad12[4];
454                 } __attribute__((__packed__, __gcc_struct__)) *a = v;
455                 a->r = puts((void*)a->p0);
456         }
457
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.
462
463 Linking
464
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.
471
472 Instead, the build process generates an object file using dynamic
473 linkage to the desired libraries. The main function is provided by
474 _cgo_main.c:
475
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) { }
481
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:
488
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"
496
497 In the end, the compiled Go package, which will eventually be
498 presented to 6l as part of a larger program, contains:
499
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
502
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.
507
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
512 the real code.
513
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.
520
521 Runtime
522
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
526 variables:
527
528         var (
529                 iscgo             bool
530                 _cgo_init         unsafe.Pointer
531                 _cgo_thread_start unsafe.Pointer
532         )
533
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
539 system calls.
540
541 Internal and External Linking
542
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.
550
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.
560
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.
564
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
571 present.)
572
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.
581
582 Linking Directives
583
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.
588
589 The directives are:
590
591 //go:cgo_import_dynamic <local> [<remote> ["<library>"]]
592
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.
598
599         In the <remote>, # or @ can be used to introduce a symbol version.
600
601         Examples:
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"
605
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.
610
611         Example:
612         //go:cgo_import_dynamic _ _ "libc.so.6"
613
614         For compatibility with current versions of SWIG,
615         #pragma dynimport is an alias for //go:cgo_import_dynamic.
616
617 //go:cgo_dynamic_linker "<path>"
618
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.
623
624         Example:
625         //go:cgo_dynamic_linker "/lib/ld-linux.so.2"
626
627 //go:cgo_export_dynamic <local> <remote>
628
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
633         to share Go's data.
634
635         For compatibility with current versions of SWIG,
636         #pragma dynexport is an alias for //go:cgo_export_dynamic.
637
638 //go:cgo_import_static <local>
639
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.
644
645         Example:
646         //go:cgo_import_static puts_wrapper
647
648 //go:cgo_export_static <local> <remote>
649
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
654         to share Go's data.
655
656 //go:cgo_ldflag "<arg>"
657
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".
661
662         Example:
663         //go:cgo_ldflag "-lpthread"
664         //go:cgo_ldflag "-L/usr/local/sqlite3/lib"
665
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.
669
670 Example
671
672 As a simple example, consider a package that uses cgo to call C.sin.
673 The following code will be generated by cgo:
674
675         // compiled by 6g
676
677         //go:cgo_ldflag "-lm"
678
679         type _Ctype_double float64
680
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)
685
686         func _Cfunc_sin(p0 _Ctype_double) (r1 _Ctype_double) {
687                 _cgo_runtime_cgocall(_cgo_gcc_Cfunc_sin, uintptr(unsafe.Pointer(&p0)))
688                 return
689         }
690
691         // compiled by gcc, into foo.cgo2.o
692
693         void
694         _cgo_gcc_Cfunc_sin(void *v)
695         {
696                 struct {
697                         double p0;
698                         double r;
699                 } __attribute__((__packed__)) *a = v;
700                 a->r = sin(a->p0);
701         }
702
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.
707
708 The linking directives are used according to the kind of final link
709 used.
710
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.
718
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
732 math library.
733
734 6l Command Line Interface
735
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:
739
740         6l main.a
741
742 produces a file named 6.out, even if 6l does so by invoking the host
743 linker in external linking mode.
744
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.
756
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.
766
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.
770
771 */