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