rsc.io/go@v0.0.0-20150416155037-e040fd465409/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 _cgo_wait_runtime_init_done(); 432 struct { 433 char* p0; 434 int r; 435 char __pad12[4]; 436 } __attribute__((__packed__, __gcc_struct__)) *a = v; 437 a->r = puts((void*)a->p0); 438 } 439 440 It waits for Go runtime to be initialized (required for shared libraries), 441 extracts the arguments from the pointer to _Cfunc_puts's argument 442 frame, invokes the system C function (in this case, puts), stores the 443 result in the frame, and returns. 444 445 Linking 446 447 Once the _cgo_export.c and *.cgo2.c files have been compiled with gcc, 448 they need to be linked into the final binary, along with the libraries 449 they might depend on (in the case of puts, stdio). 6l has been 450 extended to understand basic ELF files, but it does not understand ELF 451 in the full complexity that modern C libraries embrace, so it cannot 452 in general generate direct references to the system libraries. 453 454 Instead, the build process generates an object file using dynamic 455 linkage to the desired libraries. The main function is provided by 456 _cgo_main.c: 457 458 int main() { return 0; } 459 void crosscall2(void(*fn)(void*, int), void *a, int c) { } 460 void _cgo_wait_runtime_init_done() { } 461 void _cgo_allocate(void *a, int c) { } 462 void _cgo_panic(void *a, int c) { } 463 464 The extra functions here are stubs to satisfy the references in the C 465 code generated for gcc. The build process links this stub, along with 466 _cgo_export.c and *.cgo2.c, into a dynamic executable and then lets 467 cgo examine the executable. Cgo records the list of shared library 468 references and resolved names and writes them into a new file 469 _cgo_import.go, which looks like: 470 471 //go:cgo_dynamic_linker "/lib64/ld-linux-x86-64.so.2" 472 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6" 473 //go:cgo_import_dynamic __libc_start_main __libc_start_main#GLIBC_2.2.5 "libc.so.6" 474 //go:cgo_import_dynamic stdout stdout#GLIBC_2.2.5 "libc.so.6" 475 //go:cgo_import_dynamic fflush fflush#GLIBC_2.2.5 "libc.so.6" 476 //go:cgo_import_dynamic _ _ "libpthread.so.0" 477 //go:cgo_import_dynamic _ _ "libc.so.6" 478 479 In the end, the compiled Go package, which will eventually be 480 presented to 6l as part of a larger program, contains: 481 482 _go_.6 # 6g-compiled object for _cgo_gotypes.go, _cgo_import.go, *.cgo1.go 483 _all.o # gcc-compiled object for _cgo_export.c, *.cgo2.c 484 485 The final program will be a dynamic executable, so that 6l can avoid 486 needing to process arbitrary .o files. It only needs to process the .o 487 files generated from C files that cgo writes, and those are much more 488 limited in the ELF or other features that they use. 489 490 In essence, the _cgo_import.6 file includes the extra linking 491 directives that 6l is not sophisticated enough to derive from _all.o 492 on its own. Similarly, the _all.o uses dynamic references to real 493 system object code because 6l is not sophisticated enough to process 494 the real code. 495 496 The main benefits of this system are that 6l remains relatively simple 497 (it does not need to implement a complete ELF and Mach-O linker) and 498 that gcc is not needed after the package is compiled. For example, 499 package net uses cgo for access to name resolution functions provided 500 by libc. Although gcc is needed to compile package net, gcc is not 501 needed to link programs that import package net. 502 503 Runtime 504 505 When using cgo, Go must not assume that it owns all details of the 506 process. In particular it needs to coordinate with C in the use of 507 threads and thread-local storage. The runtime package declares a few 508 variables: 509 510 var ( 511 iscgo bool 512 _cgo_init unsafe.Pointer 513 _cgo_thread_start unsafe.Pointer 514 ) 515 516 Any package using cgo imports "runtime/cgo", which provides 517 initializations for these variables. It sets iscgo to true, _cgo_init 518 to a gcc-compiled function that can be called early during program 519 startup, and _cgo_thread_start to a gcc-compiled function that can be 520 used to create a new thread, in place of the runtime's usual direct 521 system calls. 522 523 Internal and External Linking 524 525 The text above describes "internal" linking, in which 6l parses and 526 links host object files (ELF, Mach-O, PE, and so on) into the final 527 executable itself. Keeping 6l simple means we cannot possibly 528 implement the full semantics of the host linker, so the kinds of 529 objects that can be linked directly into the binary is limited (other 530 code can only be used as a dynamic library). On the other hand, when 531 using internal linking, 6l can generate Go binaries by itself. 532 533 In order to allow linking arbitrary object files without requiring 534 dynamic libraries, cgo supports an "external" linking mode too. In 535 external linking mode, 6l does not process any host object files. 536 Instead, it collects all the Go code and writes a single go.o object 537 file containing it. Then it invokes the host linker (usually gcc) to 538 combine the go.o object file and any supporting non-Go code into a 539 final executable. External linking avoids the dynamic library 540 requirement but introduces a requirement that the host linker be 541 present to create such a binary. 542 543 Most builds both compile source code and invoke the linker to create a 544 binary. When cgo is involved, the compile step already requires gcc, so 545 it is not problematic for the link step to require gcc too. 546 547 An important exception is builds using a pre-compiled copy of the 548 standard library. In particular, package net uses cgo on most systems, 549 and we want to preserve the ability to compile pure Go code that 550 imports net without requiring gcc to be present at link time. (In this 551 case, the dynamic library requirement is less significant, because the 552 only library involved is libc.so, which can usually be assumed 553 present.) 554 555 This conflict between functionality and the gcc requirement means we 556 must support both internal and external linking, depending on the 557 circumstances: if net is the only cgo-using package, then internal 558 linking is probably fine, but if other packages are involved, so that there 559 are dependencies on libraries beyond libc, external linking is likely 560 to work better. The compilation of a package records the relevant 561 information to support both linking modes, leaving the decision 562 to be made when linking the final binary. 563 564 Linking Directives 565 566 In either linking mode, package-specific directives must be passed 567 through to 6l. These are communicated by writing //go: directives in a 568 Go source file compiled by 6g. The directives are copied into the .6 569 object file and then processed by the linker. 570 571 The directives are: 572 573 //go:cgo_import_dynamic <local> [<remote> ["<library>"]] 574 575 In internal linking mode, allow an unresolved reference to 576 <local>, assuming it will be resolved by a dynamic library 577 symbol. The optional <remote> specifies the symbol's name and 578 possibly version in the dynamic library, and the optional "<library>" 579 names the specific library where the symbol should be found. 580 581 In the <remote>, # or @ can be used to introduce a symbol version. 582 583 Examples: 584 //go:cgo_import_dynamic puts 585 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5 586 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6" 587 588 A side effect of the cgo_import_dynamic directive with a 589 library is to make the final binary depend on that dynamic 590 library. To get the dependency without importing any specific 591 symbols, use _ for local and remote. 592 593 Example: 594 //go:cgo_import_dynamic _ _ "libc.so.6" 595 596 For compatibility with current versions of SWIG, 597 #pragma dynimport is an alias for //go:cgo_import_dynamic. 598 599 //go:cgo_dynamic_linker "<path>" 600 601 In internal linking mode, use "<path>" as the dynamic linker 602 in the final binary. This directive is only needed from one 603 package when constructing a binary; by convention it is 604 supplied by runtime/cgo. 605 606 Example: 607 //go:cgo_dynamic_linker "/lib/ld-linux.so.2" 608 609 //go:cgo_export_dynamic <local> <remote> 610 611 In internal linking mode, put the Go symbol 612 named <local> into the program's exported symbol table as 613 <remote>, so that C code can refer to it by that name. This 614 mechanism makes it possible for C code to call back into Go or 615 to share Go's data. 616 617 For compatibility with current versions of SWIG, 618 #pragma dynexport is an alias for //go:cgo_export_dynamic. 619 620 //go:cgo_import_static <local> 621 622 In external linking mode, allow unresolved references to 623 <local> in the go.o object file prepared for the host linker, 624 under the assumption that <local> will be supplied by the 625 other object files that will be linked with go.o. 626 627 Example: 628 //go:cgo_import_static puts_wrapper 629 630 //go:cgo_export_static <local> <remote> 631 632 In external linking mode, put the Go symbol 633 named <local> into the program's exported symbol table as 634 <remote>, so that C code can refer to it by that name. This 635 mechanism makes it possible for C code to call back into Go or 636 to share Go's data. 637 638 //go:cgo_ldflag "<arg>" 639 640 In external linking mode, invoke the host linker (usually gcc) 641 with "<arg>" as a command-line argument following the .o files. 642 Note that the arguments are for "gcc", not "ld". 643 644 Example: 645 //go:cgo_ldflag "-lpthread" 646 //go:cgo_ldflag "-L/usr/local/sqlite3/lib" 647 648 A package compiled with cgo will include directives for both 649 internal and external linking; the linker will select the appropriate 650 subset for the chosen linking mode. 651 652 Example 653 654 As a simple example, consider a package that uses cgo to call C.sin. 655 The following code will be generated by cgo: 656 657 // compiled by 6g 658 659 //go:cgo_ldflag "-lm" 660 661 type _Ctype_double float64 662 663 //go:cgo_import_static _cgo_gcc_Cfunc_sin 664 //go:linkname __cgo_gcc_Cfunc_sin _cgo_gcc_Cfunc_sin 665 var __cgo_gcc_Cfunc_sin byte 666 var _cgo_gcc_Cfunc_sin = unsafe.Pointer(&__cgo_gcc_Cfunc_sin) 667 668 func _Cfunc_sin(p0 _Ctype_double) (r1 _Ctype_double) { 669 _cgo_runtime_cgocall_errno(_cgo_gcc_Cfunc_sin, uintptr(unsafe.Pointer(&p0))) 670 return 671 } 672 673 // compiled by gcc, into foo.cgo2.o 674 675 void 676 _cgo_gcc_Cfunc_sin(void *v) 677 { 678 struct { 679 double p0; 680 double r; 681 } __attribute__((__packed__)) *a = v; 682 a->r = sin(a->p0); 683 } 684 685 What happens at link time depends on whether the final binary is linked 686 using the internal or external mode. If other packages are compiled in 687 "external only" mode, then the final link will be an external one. 688 Otherwise the link will be an internal one. 689 690 The linking directives are used according to the kind of final link 691 used. 692 693 In internal mode, 6l itself processes all the host object files, in 694 particular foo.cgo2.o. To do so, it uses the cgo_import_dynamic and 695 cgo_dynamic_linker directives to learn that the otherwise undefined 696 reference to sin in foo.cgo2.o should be rewritten to refer to the 697 symbol sin with version GLIBC_2.2.5 from the dynamic library 698 "libm.so.6", and the binary should request "/lib/ld-linux.so.2" as its 699 runtime dynamic linker. 700 701 In external mode, 6l does not process any host object files, in 702 particular foo.cgo2.o. It links together the 6g-generated object 703 files, along with any other Go code, into a go.o file. While doing 704 that, 6l will discover that there is no definition for 705 _cgo_gcc_Cfunc_sin, referred to by the 6g-compiled source file. This 706 is okay, because 6l also processes the cgo_import_static directive and 707 knows that _cgo_gcc_Cfunc_sin is expected to be supplied by a host 708 object file, so 6l does not treat the missing symbol as an error when 709 creating go.o. Indeed, the definition for _cgo_gcc_Cfunc_sin will be 710 provided to the host linker by foo2.cgo.o, which in turn will need the 711 symbol 'sin'. 6l also processes the cgo_ldflag directives, so that it 712 knows that the eventual host link command must include the -lm 713 argument, so that the host linker will be able to find 'sin' in the 714 math library. 715 716 6l Command Line Interface 717 718 The go command and any other Go-aware build systems invoke 6l 719 to link a collection of packages into a single binary. By default, 6l will 720 present the same interface it does today: 721 722 6l main.a 723 724 produces a file named 6.out, even if 6l does so by invoking the host 725 linker in external linking mode. 726 727 By default, 6l will decide the linking mode as follows: if the only 728 packages using cgo are those on a whitelist of standard library 729 packages (net, os/user, runtime/cgo), 6l will use internal linking 730 mode. Otherwise, there are non-standard cgo packages involved, and 6l 731 will use external linking mode. The first rule means that a build of 732 the godoc binary, which uses net but no other cgo, can run without 733 needing gcc available. The second rule means that a build of a 734 cgo-wrapped library like sqlite3 can generate a standalone executable 735 instead of needing to refer to a dynamic library. The specific choice 736 can be overridden using a command line flag: 6l -linkmode=internal or 737 6l -linkmode=external. 738 739 In an external link, 6l will create a temporary directory, write any 740 host object files found in package archives to that directory (renamed 741 to avoid conflicts), write the go.o file to that directory, and invoke 742 the host linker. The default value for the host linker is $CC, split 743 into fields, or else "gcc". The specific host linker command line can 744 be overridden using command line flags: 6l -extld=clang 745 -extldflags='-ggdb -O3'. If any package in a build includes a .cc or 746 other file compiled by the C++ compiler, the go tool will use the 747 -extld option to set the host linker to the C++ compiler. 748 749 These defaults mean that Go-aware build systems can ignore the linking 750 changes and keep running plain '6l' and get reasonable results, but 751 they can also control the linking details if desired. 752 753 */