github.com/reiver/go@v0.0.0-20150109200633-1d0c7792f172/src/cmd/cgo/doc.go (about)

     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  See $GOROOT/misc/cgo/stdio and $GOROOT/misc/cgo/gmp for examples.  See
    24  "C? Go? Cgo!" for an introduction to using cgo:
    25  http://golang.org/doc/articles/c_go_cgo.html.
    26  
    27  CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS may be defined with pseudo #cgo
    28  directives within these comments to tweak the behavior of the C or C++
    29  compiler.  Values defined in multiple directives are concatenated
    30  together.  The directive can include a list of build constraints limiting its
    31  effect to systems satisfying one of the constraints
    32  (see http://golang.org/pkg/go/build/#hdr-Build_Constraints for details about the constraint syntax).
    33  For example:
    34  
    35  	// #cgo CFLAGS: -DPNG_DEBUG=1
    36  	// #cgo amd64 386 CFLAGS: -DX86=1
    37  	// #cgo LDFLAGS: -lpng
    38  	// #include <png.h>
    39  	import "C"
    40  
    41  Alternatively, CPPFLAGS and LDFLAGS may be obtained via the pkg-config
    42  tool using a '#cgo pkg-config:' directive followed by the package names.
    43  For example:
    44  
    45  	// #cgo pkg-config: png cairo
    46  	// #include <png.h>
    47  	import "C"
    48  
    49  When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS and
    50  CGO_LDFLAGS environment variables are added to the flags derived from
    51  these directives.  Package-specific flags should be set using the
    52  directives, not the environment variables, so that builds work in
    53  unmodified environments.
    54  
    55  All the cgo CPPFLAGS and CFLAGS directives in a package are concatenated and
    56  used to compile C files in that package.  All the CPPFLAGS and CXXFLAGS
    57  directives in a package are concatenated and used to compile C++ files in that
    58  package.  All the LDFLAGS directives in any package in the program are
    59  concatenated and used at link time.  All the pkg-config directives are
    60  concatenated and sent to pkg-config simultaneously to add to each appropriate
    61  set of command-line flags.
    62  
    63  When the cgo directives are parsed, any occurrence of the string ${SRCDIR}
    64  will be replaced by the absolute path to the directory containing the source
    65  file. This allows pre-compiled static libraries to be included in the package
    66  directory and linked properly.
    67  For example if package foo is in the directory /go/src/foo:
    68  
    69         // #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo
    70  
    71  Will be expanded to:
    72  
    73         // #cgo LDFLAGS: -L/go/src/foo/libs -lfoo
    74  
    75  When the Go tool sees that one or more Go files use the special import
    76  "C", it will look for other non-Go files in the directory and compile
    77  them as part of the Go package.  Any .c, .s, or .S files will be
    78  compiled with the C compiler.  Any .cc, .cpp, or .cxx files will be
    79  compiled with the C++ compiler.  Any .h, .hh, .hpp, or .hxx files will
    80  not be compiled separately, but, if these header files are changed,
    81  the C and C++ files will be recompiled.  The default C and C++
    82  compilers may be changed by the CC and CXX environment variables,
    83  respectively; those environment variables may include command line
    84  options.
    85  
    86  To enable cgo during cross compiling builds, set the CGO_ENABLED
    87  environment variable to 1 when building the Go tools with make.bash.
    88  Also, set CC_FOR_TARGET to the C cross compiler for the target.  CC will
    89  be used for compiling for the host.
    90  
    91  After the Go tools are built, when running the go command, CC_FOR_TARGET is
    92  ignored.  The value of CC_FOR_TARGET when running make.bash is the default
    93  compiler.  However, you can set the environment variable CC, not CC_FOR_TARGET,
    94  to control the compiler when running the go tool.
    95  
    96  CXX_FOR_TARGET works in a similar way for C++ code.
    97  
    98  Go references to C
    99  
   100  Within the Go file, C's struct field names that are keywords in Go
   101  can be accessed by prefixing them with an underscore: if x points at a C
   102  struct with a field named "type", x._type accesses the field.
   103  C struct fields that cannot be expressed in Go, such as bit fields
   104  or misaligned data, are omitted in the Go struct, replaced by
   105  appropriate padding to reach the next field or the end of the struct.
   106  
   107  The standard C numeric types are available under the names
   108  C.char, C.schar (signed char), C.uchar (unsigned char),
   109  C.short, C.ushort (unsigned short), C.int, C.uint (unsigned int),
   110  C.long, C.ulong (unsigned long), C.longlong (long long),
   111  C.ulonglong (unsigned long long), C.float, C.double.
   112  The C type void* is represented by Go's unsafe.Pointer.
   113  
   114  To access a struct, union, or enum type directly, prefix it with
   115  struct_, union_, or enum_, as in C.struct_stat.
   116  
   117  As Go doesn't have support for C's union type in the general case,
   118  C's union types are represented as a Go byte array with the same length.
   119  
   120  Go structs cannot embed fields with C types.
   121  
   122  Cgo translates C types into equivalent unexported Go types.
   123  Because the translations are unexported, a Go package should not
   124  expose C types in its exported API: a C type used in one Go package
   125  is different from the same C type used in another.
   126  
   127  Any C function (even void functions) may be called in a multiple
   128  assignment context to retrieve both the return value (if any) and the
   129  C errno variable as an error (use _ to skip the result value if the
   130  function returns void).  For example:
   131  
   132  	n, err := C.sqrt(-1)
   133  	_, err := C.voidFunc()
   134  
   135  Calling C function pointers is currently not supported, however you can
   136  declare Go variables which hold C function pointers and pass them
   137  back and forth between Go and C. C code may call function pointers
   138  received from Go. For example:
   139  
   140  	package main
   141  
   142  	// typedef int (*intFunc) ();
   143  	//
   144  	// int
   145  	// bridge_int_func(intFunc f)
   146  	// {
   147  	//		return f();
   148  	// }
   149  	//
   150  	// int fortytwo()
   151  	// {
   152  	//	    return 42;
   153  	// }
   154  	import "C"
   155  	import "fmt"
   156  
   157  	func main() {
   158  		f := C.intFunc(C.fortytwo)
   159  		fmt.Println(int(C.bridge_int_func(f)))
   160  		// Output: 42
   161  	}
   162  
   163  In C, a function argument written as a fixed size array
   164  actually requires a pointer to the first element of the array.
   165  C compilers are aware of this calling convention and adjust
   166  the call accordingly, but Go cannot.  In Go, you must pass
   167  the pointer to the first element explicitly: C.f(&C.x[0]).
   168  
   169  A few special functions convert between Go and C types
   170  by making copies of the data.  In pseudo-Go definitions:
   171  
   172  	// Go string to C string
   173  	// The C string is allocated in the C heap using malloc.
   174  	// It is the caller's responsibility to arrange for it to be
   175  	// freed, such as by calling C.free (be sure to include stdlib.h
   176  	// if C.free is needed).
   177  	func C.CString(string) *C.char
   178  
   179  	// C string to Go string
   180  	func C.GoString(*C.char) string
   181  
   182  	// C string, length to Go string
   183  	func C.GoStringN(*C.char, C.int) string
   184  
   185  	// C pointer, length to Go []byte
   186  	func C.GoBytes(unsafe.Pointer, C.int) []byte
   187  
   188  C references to Go
   189  
   190  Go functions can be exported for use by C code in the following way:
   191  
   192  	//export MyFunction
   193  	func MyFunction(arg1, arg2 int, arg3 string) int64 {...}
   194  
   195  	//export MyFunction2
   196  	func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
   197  
   198  They will be available in the C code as:
   199  
   200  	extern int64 MyFunction(int arg1, int arg2, GoString arg3);
   201  	extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);
   202  
   203  found in the _cgo_export.h generated header, after any preambles
   204  copied from the cgo input files. Functions with multiple
   205  return values are mapped to functions returning a struct.
   206  Not all Go types can be mapped to C types in a useful way.
   207  
   208  Using //export in a file places a restriction on the preamble:
   209  since it is copied into two different C output files, it must not
   210  contain any definitions, only declarations. Definitions must be
   211  placed in preambles in other files, or in C source files.
   212  
   213  Using cgo directly
   214  
   215  Usage:
   216  	go tool cgo [cgo options] [-- compiler options] gofiles...
   217  
   218  Cgo transforms the specified input Go source files into several output
   219  Go and C source files.
   220  
   221  The compiler options are passed through uninterpreted when
   222  invoking the C compiler to compile the C parts of the package.
   223  
   224  The following options are available when running cgo directly:
   225  
   226  	-dynimport file
   227  		Write list of symbols imported by file. Write to
   228  		-dynout argument or to standard output. Used by go
   229  		build when building a cgo package.
   230  	-dynout file
   231  		Write -dynimport output to file.
   232  	-dynpackage package
   233  		Set Go package for -dynimport output.
   234  	-dynlinker
   235  		Write dynamic linker as part of -dynimport output.
   236  	-godefs
   237  		Write out input file in Go syntax replacing C package
   238  		names with real values. Used to generate files in the
   239  		syscall package when bootstrapping a new target.
   240  	-objdir directory
   241  		Put all generated files in directory.
   242  	-gccgo
   243  		Generate output for the gccgo compiler rather than the
   244  		gc compiler.
   245  	-gccgoprefix prefix
   246  		The -fgo-prefix option to be used with gccgo.
   247  	-gccgopkgpath path
   248  		The -fgo-pkgpath option to be used with gccgo.
   249  	-import_runtime_cgo
   250  		If set (which it is by default) import runtime/cgo in
   251  		generated output.
   252  	-import_syscall
   253  		If set (which it is by default) import syscall in
   254  		generated output.
   255  	-debug-define
   256  		Debugging option. Print #defines.
   257  	-debug-gcc
   258  		Debugging option. Trace C compiler execution and output.
   259  */
   260  package main
   261  
   262  /*
   263  Implementation details.
   264  
   265  Cgo provides a way for Go programs to call C code linked into the same
   266  address space. This comment explains the operation of cgo.
   267  
   268  Cgo reads a set of Go source files and looks for statements saying
   269  import "C". If the import has a doc comment, that comment is
   270  taken as literal C code to be used as a preamble to any C code
   271  generated by cgo. A typical preamble #includes necessary definitions:
   272  
   273  	// #include <stdio.h>
   274  	import "C"
   275  
   276  For more details about the usage of cgo, see the documentation
   277  comment at the top of this file.
   278  
   279  Understanding C
   280  
   281  Cgo scans the Go source files that import "C" for uses of that
   282  package, such as C.puts. It collects all such identifiers. The next
   283  step is to determine each kind of name. In C.xxx the xxx might refer
   284  to a type, a function, a constant, or a global variable. Cgo must
   285  decide which.
   286  
   287  The obvious thing for cgo to do is to process the preamble, expanding
   288  #includes and processing the corresponding C code. That would require
   289  a full C parser and type checker that was also aware of any extensions
   290  known to the system compiler (for example, all the GNU C extensions) as
   291  well as the system-specific header locations and system-specific
   292  pre-#defined macros. This is certainly possible to do, but it is an
   293  enormous amount of work.
   294  
   295  Cgo takes a different approach. It determines the meaning of C
   296  identifiers not by parsing C code but by feeding carefully constructed
   297  programs into the system C compiler and interpreting the generated
   298  error messages, debug information, and object files. In practice,
   299  parsing these is significantly less work and more robust than parsing
   300  C source.
   301  
   302  Cgo first invokes gcc -E -dM on the preamble, in order to find out
   303  about simple #defines for constants and the like. These are recorded
   304  for later use.
   305  
   306  Next, cgo needs to identify the kinds for each identifier. For the
   307  identifiers C.foo and C.bar, cgo generates this C program:
   308  
   309  	<preamble>
   310  	#line 1 "not-declared"
   311  	void __cgo_f_xxx_1(void) { __typeof__(foo) *__cgo_undefined__; }
   312  	#line 1 "not-type"
   313  	void __cgo_f_xxx_2(void) { foo *__cgo_undefined__; }
   314  	#line 1 "not-const"
   315  	void __cgo_f_xxx_3(void) { enum { __cgo_undefined__ = (foo)*1 }; }
   316  	#line 2 "not-declared"
   317  	void __cgo_f_xxx_1(void) { __typeof__(bar) *__cgo_undefined__; }
   318  	#line 2 "not-type"
   319  	void __cgo_f_xxx_2(void) { bar *__cgo_undefined__; }
   320  	#line 2 "not-const"
   321  	void __cgo_f_xxx_3(void) { enum { __cgo_undefined__ = (bar)*1 }; }
   322  
   323  This program will not compile, but cgo can use the presence or absence
   324  of an error message on a given line to deduce the information it
   325  needs. The program is syntactically valid regardless of whether each
   326  name is a type or an ordinary identifier, so there will be no syntax
   327  errors that might stop parsing early.
   328  
   329  An error on not-declared:1 indicates that foo is undeclared.
   330  An error on not-type:1 indicates that foo is not a type (if declared at all, it is an identifier).
   331  An error on not-const:1 indicates that foo is not an integer constant.
   332  
   333  The line number specifies the name involved. In the example, 1 is foo and 2 is bar.
   334  
   335  Next, cgo must learn the details of each type, variable, function, or
   336  constant. It can do this by reading object files. If cgo has decided
   337  that t1 is a type, v2 and v3 are variables or functions, and c4, c5,
   338  and c6 are constants, it generates:
   339  
   340  	<preamble>
   341  	__typeof__(t1) *__cgo__1;
   342  	__typeof__(v2) *__cgo__2;
   343  	__typeof__(v3) *__cgo__3;
   344  	__typeof__(c4) *__cgo__4;
   345  	enum { __cgo_enum__4 = c4 };
   346  	__typeof__(c5) *__cgo__5;
   347  	enum { __cgo_enum__5 = c5 };
   348  	__typeof__(c6) *__cgo__6;
   349  	enum { __cgo_enum__6 = c6 };
   350  
   351  	long long __cgo_debug_data[] = {
   352  		0, // t1
   353  		0, // v2
   354  		0, // v3
   355  		c4,
   356  		c5,
   357  		c6,
   358  		1
   359  	};
   360  
   361  and again invokes the system C compiler, to produce an object file
   362  containing debug information. Cgo parses the DWARF debug information
   363  for __cgo__N to learn the type of each identifier. (The types also
   364  distinguish functions from global variables.) If using a standard gcc,
   365  cgo can parse the DWARF debug information for the __cgo_enum__N to
   366  learn the identifier's value. The LLVM-based gcc on OS X emits
   367  incomplete DWARF information for enums; in that case cgo reads the
   368  constant values from the __cgo_debug_data from the object file's data
   369  segment.
   370  
   371  At this point cgo knows the meaning of each C.xxx well enough to start
   372  the translation process.
   373  
   374  Translating Go
   375  
   376  [The rest of this comment refers to 6g, the Go compiler that is part
   377  of the amd64 port of the gc Go toolchain. Everything here applies to
   378  another architecture's compilers as well.]
   379  
   380  Given the input Go files x.go and y.go, cgo generates these source
   381  files:
   382  
   383  	x.cgo1.go       # for 6g
   384  	y.cgo1.go       # for 6g
   385  	_cgo_gotypes.go # for 6g
   386  	_cgo_import.go  # for 6g (if -dynout _cgo_import.go)
   387  	x.cgo2.c        # for gcc
   388  	y.cgo2.c        # for gcc
   389  	_cgo_defun.c    # for gcc (if -gccgo)
   390  	_cgo_export.c   # for gcc
   391  	_cgo_export.h   # for gcc
   392  	_cgo_main.c     # for gcc
   393  	_cgo_flags      # for alternative build tools
   394  
   395  The file x.cgo1.go is a copy of x.go with the import "C" removed and
   396  references to C.xxx replaced with names like _Cfunc_xxx or _Ctype_xxx.
   397  The definitions of those identifiers, written as Go functions, types,
   398  or variables, are provided in _cgo_gotypes.go.
   399  
   400  Here is a _cgo_gotypes.go containing definitions for needed C types:
   401  
   402  	type _Ctype_char int8
   403  	type _Ctype_int int32
   404  	type _Ctype_void [0]byte
   405  
   406  The _cgo_gotypes.go file also contains the definitions of the
   407  functions.  They all have similar bodies that invoke runtime·cgocall
   408  to make a switch from the Go runtime world to the system C (GCC-based)
   409  world.
   410  
   411  For example, here is the definition of _Cfunc_puts:
   412  
   413  	//go:cgo_import_static _cgo_be59f0f25121_Cfunc_puts
   414  	//go:linkname __cgofn__cgo_be59f0f25121_Cfunc_puts _cgo_be59f0f25121_Cfunc_puts
   415  	var __cgofn__cgo_be59f0f25121_Cfunc_puts byte
   416  	var _cgo_be59f0f25121_Cfunc_puts = unsafe.Pointer(&__cgofn__cgo_be59f0f25121_Cfunc_puts)
   417  
   418  	func _Cfunc_puts(p0 *_Ctype_char) (r1 _Ctype_int) {
   419  		_cgo_runtime_cgocall_errno(_cgo_be59f0f25121_Cfunc_puts, uintptr(unsafe.Pointer(&p0)))
   420  		return
   421  	}
   422  
   423  The hexadecimal number is a hash of cgo's input, chosen to be
   424  deterministic yet unlikely to collide with other uses. The actual
   425  function _cgo_be59f0f25121_Cfunc_puts is implemented in a C source
   426  file compiled by gcc, the file x.cgo2.c:
   427  
   428  	void
   429  	_cgo_be59f0f25121_Cfunc_puts(void *v)
   430  	{
   431  		struct {
   432  			char* p0;
   433  			int r;
   434  			char __pad12[4];
   435  		} __attribute__((__packed__, __gcc_struct__)) *a = v;
   436  		a->r = puts((void*)a->p0);
   437  	}
   438  
   439  It extracts the arguments from the pointer to _Cfunc_puts's argument
   440  frame, invokes the system C function (in this case, puts), stores the
   441  result in the frame, and returns.
   442  
   443  Linking
   444  
   445  Once the _cgo_export.c and *.cgo2.c files have been compiled with gcc,
   446  they need to be linked into the final binary, along with the libraries
   447  they might depend on (in the case of puts, stdio). 6l has been
   448  extended to understand basic ELF files, but it does not understand ELF
   449  in the full complexity that modern C libraries embrace, so it cannot
   450  in general generate direct references to the system libraries.
   451  
   452  Instead, the build process generates an object file using dynamic
   453  linkage to the desired libraries. The main function is provided by
   454  _cgo_main.c:
   455  
   456  	int main() { return 0; }
   457  	void crosscall2(void(*fn)(void*, int), void *a, int c) { }
   458  	void _cgo_allocate(void *a, int c) { }
   459  	void _cgo_panic(void *a, int c) { }
   460  
   461  The extra functions here are stubs to satisfy the references in the C
   462  code generated for gcc. The build process links this stub, along with
   463  _cgo_export.c and *.cgo2.c, into a dynamic executable and then lets
   464  cgo examine the executable. Cgo records the list of shared library
   465  references and resolved names and writes them into a new file
   466  _cgo_import.go, which looks like:
   467  
   468  	//go:cgo_dynamic_linker "/lib64/ld-linux-x86-64.so.2"
   469  	//go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6"
   470  	//go:cgo_import_dynamic __libc_start_main __libc_start_main#GLIBC_2.2.5 "libc.so.6"
   471  	//go:cgo_import_dynamic stdout stdout#GLIBC_2.2.5 "libc.so.6"
   472  	//go:cgo_import_dynamic fflush fflush#GLIBC_2.2.5 "libc.so.6"
   473  	//go:cgo_import_dynamic _ _ "libpthread.so.0"
   474  	//go:cgo_import_dynamic _ _ "libc.so.6"
   475  
   476  In the end, the compiled Go package, which will eventually be
   477  presented to 6l as part of a larger program, contains:
   478  
   479  	_go_.6        # 6g-compiled object for _cgo_gotypes.go, _cgo_import.go, *.cgo1.go
   480  	_all.o        # gcc-compiled object for _cgo_export.c, *.cgo2.c
   481  
   482  The final program will be a dynamic executable, so that 6l can avoid
   483  needing to process arbitrary .o files. It only needs to process the .o
   484  files generated from C files that cgo writes, and those are much more
   485  limited in the ELF or other features that they use.
   486  
   487  In essence, the _cgo_import.6 file includes the extra linking
   488  directives that 6l is not sophisticated enough to derive from _all.o
   489  on its own. Similarly, the _all.o uses dynamic references to real
   490  system object code because 6l is not sophisticated enough to process
   491  the real code.
   492  
   493  The main benefits of this system are that 6l remains relatively simple
   494  (it does not need to implement a complete ELF and Mach-O linker) and
   495  that gcc is not needed after the package is compiled. For example,
   496  package net uses cgo for access to name resolution functions provided
   497  by libc. Although gcc is needed to compile package net, gcc is not
   498  needed to link programs that import package net.
   499  
   500  Runtime
   501  
   502  When using cgo, Go must not assume that it owns all details of the
   503  process. In particular it needs to coordinate with C in the use of
   504  threads and thread-local storage. The runtime package declares a few
   505  variables:
   506  
   507  	var (
   508  		iscgo             bool
   509  		_cgo_init         unsafe.Pointer
   510  		_cgo_thread_start unsafe.Pointer
   511  	)
   512  
   513  Any package using cgo imports "runtime/cgo", which provides
   514  initializations for these variables. It sets iscgo to true, _cgo_init
   515  to a gcc-compiled function that can be called early during program
   516  startup, and _cgo_thread_start to a gcc-compiled function that can be
   517  used to create a new thread, in place of the runtime's usual direct
   518  system calls.
   519  
   520  Internal and External Linking
   521  
   522  The text above describes "internal" linking, in which 6l parses and
   523  links host object files (ELF, Mach-O, PE, and so on) into the final
   524  executable itself. Keeping 6l simple means we cannot possibly
   525  implement the full semantics of the host linker, so the kinds of
   526  objects that can be linked directly into the binary is limited (other
   527  code can only be used as a dynamic library). On the other hand, when
   528  using internal linking, 6l can generate Go binaries by itself.
   529  
   530  In order to allow linking arbitrary object files without requiring
   531  dynamic libraries, cgo supports an "external" linking mode too. In
   532  external linking mode, 6l does not process any host object files.
   533  Instead, it collects all the Go code and writes a single go.o object
   534  file containing it. Then it invokes the host linker (usually gcc) to
   535  combine the go.o object file and any supporting non-Go code into a
   536  final executable. External linking avoids the dynamic library
   537  requirement but introduces a requirement that the host linker be
   538  present to create such a binary.
   539  
   540  Most builds both compile source code and invoke the linker to create a
   541  binary. When cgo is involved, the compile step already requires gcc, so
   542  it is not problematic for the link step to require gcc too.
   543  
   544  An important exception is builds using a pre-compiled copy of the
   545  standard library. In particular, package net uses cgo on most systems,
   546  and we want to preserve the ability to compile pure Go code that
   547  imports net without requiring gcc to be present at link time. (In this
   548  case, the dynamic library requirement is less significant, because the
   549  only library involved is libc.so, which can usually be assumed
   550  present.)
   551  
   552  This conflict between functionality and the gcc requirement means we
   553  must support both internal and external linking, depending on the
   554  circumstances: if net is the only cgo-using package, then internal
   555  linking is probably fine, but if other packages are involved, so that there
   556  are dependencies on libraries beyond libc, external linking is likely
   557  to work better. The compilation of a package records the relevant
   558  information to support both linking modes, leaving the decision
   559  to be made when linking the final binary.
   560  
   561  Linking Directives
   562  
   563  In either linking mode, package-specific directives must be passed
   564  through to 6l. These are communicated by writing //go: directives in a
   565  Go source file compiled by 6g. The directives are copied into the .6
   566  object file and then processed by the linker.
   567  
   568  The directives are:
   569  
   570  //go:cgo_import_dynamic <local> [<remote> ["<library>"]]
   571  
   572  	In internal linking mode, allow an unresolved reference to
   573  	<local>, assuming it will be resolved by a dynamic library
   574  	symbol. The optional <remote> specifies the symbol's name and
   575  	possibly version in the dynamic library, and the optional "<library>"
   576  	names the specific library where the symbol should be found.
   577  
   578  	In the <remote>, # or @ can be used to introduce a symbol version.
   579  
   580  	Examples:
   581  	//go:cgo_import_dynamic puts
   582  	//go:cgo_import_dynamic puts puts#GLIBC_2.2.5
   583  	//go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6"
   584  
   585  	A side effect of the cgo_import_dynamic directive with a
   586  	library is to make the final binary depend on that dynamic
   587  	library. To get the dependency without importing any specific
   588  	symbols, use _ for local and remote.
   589  
   590  	Example:
   591  	//go:cgo_import_dynamic _ _ "libc.so.6"
   592  
   593  	For compatibility with current versions of SWIG,
   594  	#pragma dynimport is an alias for //go:cgo_import_dynamic.
   595  
   596  //go:cgo_dynamic_linker "<path>"
   597  
   598  	In internal linking mode, use "<path>" as the dynamic linker
   599  	in the final binary. This directive is only needed from one
   600  	package when constructing a binary; by convention it is
   601  	supplied by runtime/cgo.
   602  
   603  	Example:
   604  	//go:cgo_dynamic_linker "/lib/ld-linux.so.2"
   605  
   606  //go:cgo_export_dynamic <local> <remote>
   607  
   608  	In internal linking mode, put the Go symbol
   609  	named <local> into the program's exported symbol table as
   610  	<remote>, so that C code can refer to it by that name. This
   611  	mechanism makes it possible for C code to call back into Go or
   612  	to share Go's data.
   613  
   614  	For compatibility with current versions of SWIG,
   615  	#pragma dynexport is an alias for //go:cgo_export_dynamic.
   616  
   617  //go:cgo_import_static <local>
   618  
   619  	In external linking mode, allow unresolved references to
   620  	<local> in the go.o object file prepared for the host linker,
   621  	under the assumption that <local> will be supplied by the
   622  	other object files that will be linked with go.o.
   623  
   624  	Example:
   625  	//go:cgo_import_static puts_wrapper
   626  
   627  //go:cgo_export_static <local> <remote>
   628  
   629  	In external 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  //go:cgo_ldflag "<arg>"
   636  
   637  	In external linking mode, invoke the host linker (usually gcc)
   638  	with "<arg>" as a command-line argument following the .o files.
   639  	Note that the arguments are for "gcc", not "ld".
   640  
   641  	Example:
   642  	//go:cgo_ldflag "-lpthread"
   643  	//go:cgo_ldflag "-L/usr/local/sqlite3/lib"
   644  
   645  A package compiled with cgo will include directives for both
   646  internal and external linking; the linker will select the appropriate
   647  subset for the chosen linking mode.
   648  
   649  Example
   650  
   651  As a simple example, consider a package that uses cgo to call C.sin.
   652  The following code will be generated by cgo:
   653  
   654  	// compiled by 6g
   655  
   656  	//go:cgo_ldflag "-lm"
   657  
   658  	type _Ctype_double float64
   659  
   660  	//go:cgo_import_static _cgo_gcc_Cfunc_sin
   661  	//go:linkname __cgo_gcc_Cfunc_sin _cgo_gcc_Cfunc_sin
   662  	var __cgo_gcc_Cfunc_sin byte
   663  	var _cgo_gcc_Cfunc_sin = unsafe.Pointer(&__cgo_gcc_Cfunc_sin)
   664  
   665  	func _Cfunc_sin(p0 _Ctype_double) (r1 _Ctype_double) {
   666  		_cgo_runtime_cgocall_errno(_cgo_gcc_Cfunc_sin, uintptr(unsafe.Pointer(&p0)))
   667  		return
   668  	}
   669  
   670  	// compiled by gcc, into foo.cgo2.o
   671  
   672  	void
   673  	_cgo_gcc_Cfunc_sin(void *v)
   674  	{
   675  		struct {
   676  			double p0;
   677  			double r;
   678  		} __attribute__((__packed__)) *a = v;
   679  		a->r = sin(a->p0);
   680  	}
   681  
   682  What happens at link time depends on whether the final binary is linked
   683  using the internal or external mode. If other packages are compiled in
   684  "external only" mode, then the final link will be an external one.
   685  Otherwise the link will be an internal one.
   686  
   687  The linking directives are used according to the kind of final link
   688  used.
   689  
   690  In internal mode, 6l itself processes all the host object files, in
   691  particular foo.cgo2.o. To do so, it uses the cgo_import_dynamic and
   692  cgo_dynamic_linker directives to learn that the otherwise undefined
   693  reference to sin in foo.cgo2.o should be rewritten to refer to the
   694  symbol sin with version GLIBC_2.2.5 from the dynamic library
   695  "libm.so.6", and the binary should request "/lib/ld-linux.so.2" as its
   696  runtime dynamic linker.
   697  
   698  In external mode, 6l does not process any host object files, in
   699  particular foo.cgo2.o. It links together the 6g-generated object
   700  files, along with any other Go code, into a go.o file. While doing
   701  that, 6l will discover that there is no definition for
   702  _cgo_gcc_Cfunc_sin, referred to by the 6g-compiled source file. This
   703  is okay, because 6l also processes the cgo_import_static directive and
   704  knows that _cgo_gcc_Cfunc_sin is expected to be supplied by a host
   705  object file, so 6l does not treat the missing symbol as an error when
   706  creating go.o. Indeed, the definition for _cgo_gcc_Cfunc_sin will be
   707  provided to the host linker by foo2.cgo.o, which in turn will need the
   708  symbol 'sin'. 6l also processes the cgo_ldflag directives, so that it
   709  knows that the eventual host link command must include the -lm
   710  argument, so that the host linker will be able to find 'sin' in the
   711  math library.
   712  
   713  6l Command Line Interface
   714  
   715  The go command and any other Go-aware build systems invoke 6l
   716  to link a collection of packages into a single binary. By default, 6l will
   717  present the same interface it does today:
   718  
   719  	6l main.a
   720  
   721  produces a file named 6.out, even if 6l does so by invoking the host
   722  linker in external linking mode.
   723  
   724  By default, 6l will decide the linking mode as follows: if the only
   725  packages using cgo are those on a whitelist of standard library
   726  packages (net, os/user, runtime/cgo), 6l will use internal linking
   727  mode. Otherwise, there are non-standard cgo packages involved, and 6l
   728  will use external linking mode. The first rule means that a build of
   729  the godoc binary, which uses net but no other cgo, can run without
   730  needing gcc available. The second rule means that a build of a
   731  cgo-wrapped library like sqlite3 can generate a standalone executable
   732  instead of needing to refer to a dynamic library. The specific choice
   733  can be overridden using a command line flag: 6l -linkmode=internal or
   734  6l -linkmode=external.
   735  
   736  In an external link, 6l will create a temporary directory, write any
   737  host object files found in package archives to that directory (renamed
   738  to avoid conflicts), write the go.o file to that directory, and invoke
   739  the host linker. The default value for the host linker is $CC, split
   740  into fields, or else "gcc". The specific host linker command line can
   741  be overridden using command line flags: 6l -extld=clang
   742  -extldflags='-ggdb -O3'.  If any package in a build includes a .cc or
   743  other file compiled by the C++ compiler, the go tool will use the
   744  -extld option to set the host linker to the C++ compiler.
   745  
   746  These defaults mean that Go-aware build systems can ignore the linking
   747  changes and keep running plain '6l' and get reasonable results, but
   748  they can also control the linking details if desired.
   749  
   750  */