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