github.com/kdevb0x/go@v0.0.0-20180115030120-39687051e9e7/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 The preamble may contain any C code, including function and variable 24 declarations and definitions. These may then be referred to from Go 25 code as though they were defined in the package "C". All names 26 declared in the preamble may be used, even if they start with a 27 lower-case letter. Exception: static variables in the preamble may 28 not be referenced from Go code; static functions are permitted. 29 30 See $GOROOT/misc/cgo/stdio and $GOROOT/misc/cgo/gmp for examples. See 31 "C? Go? Cgo!" for an introduction to using cgo: 32 https://golang.org/doc/articles/c_go_cgo.html. 33 34 CFLAGS, CPPFLAGS, CXXFLAGS, FFLAGS and LDFLAGS may be defined with pseudo 35 #cgo directives within these comments to tweak the behavior of the C, C++ 36 or Fortran compiler. Values defined in multiple directives are concatenated 37 together. The directive can include a list of build constraints limiting its 38 effect to systems satisfying one of the constraints 39 (see https://golang.org/pkg/go/build/#hdr-Build_Constraints for details about the constraint syntax). 40 For example: 41 42 // #cgo CFLAGS: -DPNG_DEBUG=1 43 // #cgo amd64 386 CFLAGS: -DX86=1 44 // #cgo LDFLAGS: -lpng 45 // #include <png.h> 46 import "C" 47 48 Alternatively, CPPFLAGS and LDFLAGS may be obtained via the pkg-config 49 tool using a '#cgo pkg-config:' directive followed by the package names. 50 For example: 51 52 // #cgo pkg-config: png cairo 53 // #include <png.h> 54 import "C" 55 56 The default pkg-config tool may be changed by setting the PKG_CONFIG environment variable. 57 58 When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS, CGO_FFLAGS and 59 CGO_LDFLAGS environment variables are added to the flags derived from 60 these directives. Package-specific flags should be set using the 61 directives, not the environment variables, so that builds work in 62 unmodified environments. 63 64 All the cgo CPPFLAGS and CFLAGS directives in a package are concatenated and 65 used to compile C files in that package. All the CPPFLAGS and CXXFLAGS 66 directives in a package are concatenated and used to compile C++ files in that 67 package. All the CPPFLAGS and FFLAGS directives in a package are concatenated 68 and used to compile Fortran files in that package. All the LDFLAGS directives 69 in any package in the program are concatenated and used at link time. All the 70 pkg-config directives are concatenated and sent to pkg-config simultaneously 71 to add to each appropriate set of command-line flags. 72 73 When the cgo directives are parsed, any occurrence of the string ${SRCDIR} 74 will be replaced by the absolute path to the directory containing the source 75 file. This allows pre-compiled static libraries to be included in the package 76 directory and linked properly. 77 For example if package foo is in the directory /go/src/foo: 78 79 // #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo 80 81 Will be expanded to: 82 83 // #cgo LDFLAGS: -L/go/src/foo/libs -lfoo 84 85 When the Go tool sees that one or more Go files use the special import 86 "C", it will look for other non-Go files in the directory and compile 87 them as part of the Go package. Any .c, .s, or .S files will be 88 compiled with the C compiler. Any .cc, .cpp, or .cxx files will be 89 compiled with the C++ compiler. Any .f, .F, .for or .f90 files will be 90 compiled with the fortran compiler. Any .h, .hh, .hpp, or .hxx files will 91 not be compiled separately, but, if these header files are changed, 92 the C and C++ files will be recompiled. The default C and C++ 93 compilers may be changed by the CC and CXX environment variables, 94 respectively; those environment variables may include command line 95 options. 96 97 The cgo tool is enabled by default for native builds on systems where 98 it is expected to work. It is disabled by default when 99 cross-compiling. You can control this by setting the CGO_ENABLED 100 environment variable when running the go tool: set it to 1 to enable 101 the use of cgo, and to 0 to disable it. The go tool will set the 102 build constraint "cgo" if cgo is enabled. 103 104 When cross-compiling, you must specify a C cross-compiler for cgo to 105 use. You can do this by setting the generic CC_FOR_TARGET or the 106 more specific CC_FOR_${GOOS}_${GOARCH} (for example, CC_FOR_linux_arm) 107 environment variable when building the toolchain using make.bash, 108 or you can set the CC environment variable any time you run the go tool. 109 110 The CXX_FOR_TARGET, CXX_FOR_${GOOS}_${GOARCH}, and CXX 111 environment variables work in a similar way for C++ code. 112 113 Go references to C 114 115 Within the Go file, C's struct field names that are keywords in Go 116 can be accessed by prefixing them with an underscore: if x points at a C 117 struct with a field named "type", x._type accesses the field. 118 C struct fields that cannot be expressed in Go, such as bit fields 119 or misaligned data, are omitted in the Go struct, replaced by 120 appropriate padding to reach the next field or the end of the struct. 121 122 The standard C numeric types are available under the names 123 C.char, C.schar (signed char), C.uchar (unsigned char), 124 C.short, C.ushort (unsigned short), C.int, C.uint (unsigned int), 125 C.long, C.ulong (unsigned long), C.longlong (long long), 126 C.ulonglong (unsigned long long), C.float, C.double, 127 C.complexfloat (complex float), and C.complexdouble (complex double). 128 The C type void* is represented by Go's unsafe.Pointer. 129 The C types __int128_t and __uint128_t are represented by [16]byte. 130 131 A few special C types which would normally be represented by a pointer 132 type in Go are instead represented by a uintptr. See the Special 133 cases section below. 134 135 To access a struct, union, or enum type directly, prefix it with 136 struct_, union_, or enum_, as in C.struct_stat. 137 138 The size of any C type T is available as C.sizeof_T, as in 139 C.sizeof_struct_stat. 140 141 A C function may be declared in the Go file with a parameter type of 142 the special name _GoString_. This function may be called with an 143 ordinary Go string value. The string length, and a pointer to the 144 string contents, may be accessed by calling the C functions 145 146 size_t _GoStringLen(_GoString_ s); 147 const char *_GoStringPtr(_GoString_ s); 148 149 These functions are only available in the preamble, not in other C 150 files. The C code must not modify the contents of the pointer returned 151 by _GoStringPtr. Note that the string contents may not have a trailing 152 NUL byte. 153 154 As Go doesn't have support for C's union type in the general case, 155 C's union types are represented as a Go byte array with the same length. 156 157 Go structs cannot embed fields with C types. 158 159 Go code cannot refer to zero-sized fields that occur at the end of 160 non-empty C structs. To get the address of such a field (which is the 161 only operation you can do with a zero-sized field) you must take the 162 address of the struct and add the size of the struct. 163 164 Cgo translates C types into equivalent unexported Go types. 165 Because the translations are unexported, a Go package should not 166 expose C types in its exported API: a C type used in one Go package 167 is different from the same C type used in another. 168 169 Any C function (even void functions) may be called in a multiple 170 assignment context to retrieve both the return value (if any) and the 171 C errno variable as an error (use _ to skip the result value if the 172 function returns void). For example: 173 174 n, err = C.sqrt(-1) 175 _, err := C.voidFunc() 176 var n, err = C.sqrt(1) 177 178 Calling C function pointers is currently not supported, however you can 179 declare Go variables which hold C function pointers and pass them 180 back and forth between Go and C. C code may call function pointers 181 received from Go. For example: 182 183 package main 184 185 // typedef int (*intFunc) (); 186 // 187 // int 188 // bridge_int_func(intFunc f) 189 // { 190 // return f(); 191 // } 192 // 193 // int fortytwo() 194 // { 195 // return 42; 196 // } 197 import "C" 198 import "fmt" 199 200 func main() { 201 f := C.intFunc(C.fortytwo) 202 fmt.Println(int(C.bridge_int_func(f))) 203 // Output: 42 204 } 205 206 In C, a function argument written as a fixed size array 207 actually requires a pointer to the first element of the array. 208 C compilers are aware of this calling convention and adjust 209 the call accordingly, but Go cannot. In Go, you must pass 210 the pointer to the first element explicitly: C.f(&C.x[0]). 211 212 A few special functions convert between Go and C types 213 by making copies of the data. In pseudo-Go definitions: 214 215 // Go string to C string 216 // The C string is allocated in the C heap using malloc. 217 // It is the caller's responsibility to arrange for it to be 218 // freed, such as by calling C.free (be sure to include stdlib.h 219 // if C.free is needed). 220 func C.CString(string) *C.char 221 222 // Go []byte slice to C array 223 // The C array is allocated in the C heap using malloc. 224 // It is the caller's responsibility to arrange for it to be 225 // freed, such as by calling C.free (be sure to include stdlib.h 226 // if C.free is needed). 227 func C.CBytes([]byte) unsafe.Pointer 228 229 // C string to Go string 230 func C.GoString(*C.char) string 231 232 // C data with explicit length to Go string 233 func C.GoStringN(*C.char, C.int) string 234 235 // C data with explicit length to Go []byte 236 func C.GoBytes(unsafe.Pointer, C.int) []byte 237 238 As a special case, C.malloc does not call the C library malloc directly 239 but instead calls a Go helper function that wraps the C library malloc 240 but guarantees never to return nil. If C's malloc indicates out of memory, 241 the helper function crashes the program, like when Go itself runs out 242 of memory. Because C.malloc cannot fail, it has no two-result form 243 that returns errno. 244 245 C references to Go 246 247 Go functions can be exported for use by C code in the following way: 248 249 //export MyFunction 250 func MyFunction(arg1, arg2 int, arg3 string) int64 {...} 251 252 //export MyFunction2 253 func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...} 254 255 They will be available in the C code as: 256 257 extern int64 MyFunction(int arg1, int arg2, GoString arg3); 258 extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3); 259 260 found in the _cgo_export.h generated header, after any preambles 261 copied from the cgo input files. Functions with multiple 262 return values are mapped to functions returning a struct. 263 264 Not all Go types can be mapped to C types in a useful way. 265 Go struct types are not supported; use a C struct type. 266 Go array types are not supported; use a C pointer. 267 268 Go functions that take arguments of type string may be called with the 269 C type _GoString_, described above. The _GoString_ type will be 270 automatically defined in the preamble. Note that there is no way for C 271 code to create a value of this type; this is only useful for passing 272 string values from Go to C and back to Go. 273 274 Using //export in a file places a restriction on the preamble: 275 since it is copied into two different C output files, it must not 276 contain any definitions, only declarations. If a file contains both 277 definitions and declarations, then the two output files will produce 278 duplicate symbols and the linker will fail. To avoid this, definitions 279 must be placed in preambles in other files, or in C source files. 280 281 Passing pointers 282 283 Go is a garbage collected language, and the garbage collector needs to 284 know the location of every pointer to Go memory. Because of this, 285 there are restrictions on passing pointers between Go and C. 286 287 In this section the term Go pointer means a pointer to memory 288 allocated by Go (such as by using the & operator or calling the 289 predefined new function) and the term C pointer means a pointer to 290 memory allocated by C (such as by a call to C.malloc). Whether a 291 pointer is a Go pointer or a C pointer is a dynamic property 292 determined by how the memory was allocated; it has nothing to do with 293 the type of the pointer. 294 295 Note that values of some Go types, other than the type's zero value, 296 always include Go pointers. This is true of string, slice, interface, 297 channel, map, and function types. A pointer type may hold a Go pointer 298 or a C pointer. Array and struct types may or may not include Go 299 pointers, depending on the element types. All the discussion below 300 about Go pointers applies not just to pointer types, but also to other 301 types that include Go pointers. 302 303 Go code may pass a Go pointer to C provided the Go memory to which it 304 points does not contain any Go pointers. The C code must preserve 305 this property: it must not store any Go pointers in Go memory, even 306 temporarily. When passing a pointer to a field in a struct, the Go 307 memory in question is the memory occupied by the field, not the entire 308 struct. When passing a pointer to an element in an array or slice, 309 the Go memory in question is the entire array or the entire backing 310 array of the slice. 311 312 C code may not keep a copy of a Go pointer after the call returns. 313 This includes the _GoString_ type, which, as noted above, includes a 314 Go pointer; _GoString_ values may not be retained by C code. 315 316 A Go function called by C code may not return a Go pointer (which 317 implies that it may not return a string, slice, channel, and so 318 forth). A Go function called by C code may take C pointers as 319 arguments, and it may store non-pointer or C pointer data through 320 those pointers, but it may not store a Go pointer in memory pointed to 321 by a C pointer. A Go function called by C code may take a Go pointer 322 as an argument, but it must preserve the property that the Go memory 323 to which it points does not contain any Go pointers. 324 325 Go code may not store a Go pointer in C memory. C code may store Go 326 pointers in C memory, subject to the rule above: it must stop storing 327 the Go pointer when the C function returns. 328 329 These rules are checked dynamically at runtime. The checking is 330 controlled by the cgocheck setting of the GODEBUG environment 331 variable. The default setting is GODEBUG=cgocheck=1, which implements 332 reasonably cheap dynamic checks. These checks may be disabled 333 entirely using GODEBUG=cgocheck=0. Complete checking of pointer 334 handling, at some cost in run time, is available via GODEBUG=cgocheck=2. 335 336 It is possible to defeat this enforcement by using the unsafe package, 337 and of course there is nothing stopping the C code from doing anything 338 it likes. However, programs that break these rules are likely to fail 339 in unexpected and unpredictable ways. 340 341 Special cases 342 343 A few special C types which would normally be represented by a pointer 344 type in Go are instead represented by a uintptr. Those types are 345 the CF*Ref types from the CoreFoundation library on Darwin, including: 346 347 CFAllocatorRef 348 CFArrayRef 349 CFAttributedStringRef 350 CFBagRef 351 CFBinaryHeapRef 352 CFBitVectorRef 353 CFBooleanRef 354 CFBundleRef 355 CFCalendarRef 356 CFCharacterSetRef 357 CFDataRef 358 CFDateFormatterRef 359 CFDateRef 360 CFDictionaryRef 361 CFErrorRef 362 CFFileDescriptorRef 363 CFFileSecurityRef 364 CFLocaleRef 365 CFMachPortRef 366 CFMessagePortRef 367 CFMutableArrayRef 368 CFMutableAttributedStringRef 369 CFMutableBagRef 370 CFMutableBitVectorRef 371 CFMutableCharacterSetRef 372 CFMutableDataRef 373 CFMutableDictionaryRef 374 CFMutableSetRef 375 CFMutableStringRef 376 CFNotificationCenterRef 377 CFNullRef 378 CFNumberFormatterRef 379 CFNumberRef 380 CFPlugInInstanceRef 381 CFPlugInRef 382 CFPropertyListRef 383 CFReadStreamRef 384 CFRunLoopObserverRef 385 CFRunLoopRef 386 CFRunLoopSourceRef 387 CFRunLoopTimerRef 388 CFSetRef 389 CFSocketRef 390 CFStringRef 391 CFStringTokenizerRef 392 CFTimeZoneRef 393 CFTreeRef 394 CFTypeRef 395 CFURLCreateFromFSRef 396 CFURLEnumeratorRef 397 CFURLGetFSRef 398 CFURLRef 399 CFUUIDRef 400 CFUserNotificationRef 401 CFWriteStreamRef 402 CFXMLNodeRef 403 CFXMLParserRef 404 CFXMLTreeRef 405 406 Also the object types from Java's JNI interface: 407 408 jobject 409 jclass 410 jthrowable 411 jstring 412 jarray 413 jbooleanArray 414 jbyteArray 415 jcharArray 416 jshortArray 417 jintArray 418 jlongArray 419 jfloatArray 420 jdoubleArray 421 jobjectArray 422 jweak 423 424 These types are uintptr on the Go side because they would otherwise 425 confuse the Go garbage collector; they are sometimes not really 426 pointers but data structures encoded in a pointer type. All operations 427 on these types must happen in C. The proper constant to initialize an 428 empty such reference is 0, not nil. 429 430 These special cases were introduced in Go 1.10. For auto-updating code 431 from Go 1.9 and earlier, use the cftype or jni rewrites in the Go fix tool: 432 433 go tool fix -r cftype <pkg> 434 go tool fix -r jni <pkg> 435 436 It will replace nil with 0 in the appropriate places. 437 438 Using cgo directly 439 440 Usage: 441 go tool cgo [cgo options] [-- compiler options] gofiles... 442 443 Cgo transforms the specified input Go source files into several output 444 Go and C source files. 445 446 The compiler options are passed through uninterpreted when 447 invoking the C compiler to compile the C parts of the package. 448 449 The following options are available when running cgo directly: 450 451 -V 452 Print cgo version and exit. 453 -debug-define 454 Debugging option. Print #defines. 455 -debug-gcc 456 Debugging option. Trace C compiler execution and output. 457 -dynimport file 458 Write list of symbols imported by file. Write to 459 -dynout argument or to standard output. Used by go 460 build when building a cgo package. 461 -dynlinker 462 Write dynamic linker as part of -dynimport output. 463 -dynout file 464 Write -dynimport output to file. 465 -dynpackage package 466 Set Go package for -dynimport output. 467 -exportheader file 468 If there are any exported functions, write the 469 generated export declarations to file. 470 C code can #include this to see the declarations. 471 -importpath string 472 The import path for the Go package. Optional; used for 473 nicer comments in the generated files. 474 -import_runtime_cgo 475 If set (which it is by default) import runtime/cgo in 476 generated output. 477 -import_syscall 478 If set (which it is by default) import syscall in 479 generated output. 480 -gccgo 481 Generate output for the gccgo compiler rather than the 482 gc compiler. 483 -gccgoprefix prefix 484 The -fgo-prefix option to be used with gccgo. 485 -gccgopkgpath path 486 The -fgo-pkgpath option to be used with gccgo. 487 -godefs 488 Write out input file in Go syntax replacing C package 489 names with real values. Used to generate files in the 490 syscall package when bootstrapping a new target. 491 -objdir directory 492 Put all generated files in directory. 493 -srcdir directory 494 */ 495 package main 496 497 /* 498 Implementation details. 499 500 Cgo provides a way for Go programs to call C code linked into the same 501 address space. This comment explains the operation of cgo. 502 503 Cgo reads a set of Go source files and looks for statements saying 504 import "C". If the import has a doc comment, that comment is 505 taken as literal C code to be used as a preamble to any C code 506 generated by cgo. A typical preamble #includes necessary definitions: 507 508 // #include <stdio.h> 509 import "C" 510 511 For more details about the usage of cgo, see the documentation 512 comment at the top of this file. 513 514 Understanding C 515 516 Cgo scans the Go source files that import "C" for uses of that 517 package, such as C.puts. It collects all such identifiers. The next 518 step is to determine each kind of name. In C.xxx the xxx might refer 519 to a type, a function, a constant, or a global variable. Cgo must 520 decide which. 521 522 The obvious thing for cgo to do is to process the preamble, expanding 523 #includes and processing the corresponding C code. That would require 524 a full C parser and type checker that was also aware of any extensions 525 known to the system compiler (for example, all the GNU C extensions) as 526 well as the system-specific header locations and system-specific 527 pre-#defined macros. This is certainly possible to do, but it is an 528 enormous amount of work. 529 530 Cgo takes a different approach. It determines the meaning of C 531 identifiers not by parsing C code but by feeding carefully constructed 532 programs into the system C compiler and interpreting the generated 533 error messages, debug information, and object files. In practice, 534 parsing these is significantly less work and more robust than parsing 535 C source. 536 537 Cgo first invokes gcc -E -dM on the preamble, in order to find out 538 about simple #defines for constants and the like. These are recorded 539 for later use. 540 541 Next, cgo needs to identify the kinds for each identifier. For the 542 identifiers C.foo, cgo generates this C program: 543 544 <preamble> 545 #line 1 "not-declared" 546 void __cgo_f_1_1(void) { __typeof__(foo) *__cgo_undefined__1; } 547 #line 1 "not-type" 548 void __cgo_f_1_2(void) { foo *__cgo_undefined__2; } 549 #line 1 "not-int-const" 550 void __cgo_f_1_3(void) { enum { __cgo_undefined__3 = (foo)*1 }; } 551 #line 1 "not-num-const" 552 void __cgo_f_1_4(void) { static const double __cgo_undefined__4 = (foo); } 553 #line 1 "not-str-lit" 554 void __cgo_f_1_5(void) { static const char __cgo_undefined__5[] = (foo); } 555 556 This program will not compile, but cgo can use the presence or absence 557 of an error message on a given line to deduce the information it 558 needs. The program is syntactically valid regardless of whether each 559 name is a type or an ordinary identifier, so there will be no syntax 560 errors that might stop parsing early. 561 562 An error on not-declared:1 indicates that foo is undeclared. 563 An error on not-type:1 indicates that foo is not a type (if declared at all, it is an identifier). 564 An error on not-int-const:1 indicates that foo is not an integer constant. 565 An error on not-num-const:1 indicates that foo is not a number constant. 566 An error on not-str-lit:1 indicates that foo is not a string literal. 567 An error on not-signed-int-const:1 indicates that foo is not a signed integer constant. 568 569 The line number specifies the name involved. In the example, 1 is foo. 570 571 Next, cgo must learn the details of each type, variable, function, or 572 constant. It can do this by reading object files. If cgo has decided 573 that t1 is a type, v2 and v3 are variables or functions, and i4, i5 574 are integer constants, u6 is an unsigned integer constant, and f7 and f8 575 are float constants, and s9 and s10 are string constants, it generates: 576 577 <preamble> 578 __typeof__(t1) *__cgo__1; 579 __typeof__(v2) *__cgo__2; 580 __typeof__(v3) *__cgo__3; 581 __typeof__(i4) *__cgo__4; 582 enum { __cgo_enum__4 = i4 }; 583 __typeof__(i5) *__cgo__5; 584 enum { __cgo_enum__5 = i5 }; 585 __typeof__(u6) *__cgo__6; 586 enum { __cgo_enum__6 = u6 }; 587 __typeof__(f7) *__cgo__7; 588 __typeof__(f8) *__cgo__8; 589 __typeof__(s9) *__cgo__9; 590 __typeof__(s10) *__cgo__10; 591 592 long long __cgodebug_ints[] = { 593 0, // t1 594 0, // v2 595 0, // v3 596 i4, 597 i5, 598 u6, 599 0, // f7 600 0, // f8 601 0, // s9 602 0, // s10 603 1 604 }; 605 606 double __cgodebug_floats[] = { 607 0, // t1 608 0, // v2 609 0, // v3 610 0, // i4 611 0, // i5 612 0, // u6 613 f7, 614 f8, 615 0, // s9 616 0, // s10 617 1 618 }; 619 620 const char __cgodebug_str__9[] = s9; 621 const unsigned long long __cgodebug_strlen__9 = sizeof(s9)-1; 622 const char __cgodebug_str__10[] = s10; 623 const unsigned long long __cgodebug_strlen__10 = sizeof(s10)-1; 624 625 and again invokes the system C compiler, to produce an object file 626 containing debug information. Cgo parses the DWARF debug information 627 for __cgo__N to learn the type of each identifier. (The types also 628 distinguish functions from global variables.) Cgo reads the constant 629 values from the __cgodebug_* from the object file's data segment. 630 631 At this point cgo knows the meaning of each C.xxx well enough to start 632 the translation process. 633 634 Translating Go 635 636 Given the input Go files x.go and y.go, cgo generates these source 637 files: 638 639 x.cgo1.go # for gc (cmd/compile) 640 y.cgo1.go # for gc 641 _cgo_gotypes.go # for gc 642 _cgo_import.go # for gc (if -dynout _cgo_import.go) 643 x.cgo2.c # for gcc 644 y.cgo2.c # for gcc 645 _cgo_defun.c # for gcc (if -gccgo) 646 _cgo_export.c # for gcc 647 _cgo_export.h # for gcc 648 _cgo_main.c # for gcc 649 _cgo_flags # for alternative build tools 650 651 The file x.cgo1.go is a copy of x.go with the import "C" removed and 652 references to C.xxx replaced with names like _Cfunc_xxx or _Ctype_xxx. 653 The definitions of those identifiers, written as Go functions, types, 654 or variables, are provided in _cgo_gotypes.go. 655 656 Here is a _cgo_gotypes.go containing definitions for needed C types: 657 658 type _Ctype_char int8 659 type _Ctype_int int32 660 type _Ctype_void [0]byte 661 662 The _cgo_gotypes.go file also contains the definitions of the 663 functions. They all have similar bodies that invoke runtime·cgocall 664 to make a switch from the Go runtime world to the system C (GCC-based) 665 world. 666 667 For example, here is the definition of _Cfunc_puts: 668 669 //go:cgo_import_static _cgo_be59f0f25121_Cfunc_puts 670 //go:linkname __cgofn__cgo_be59f0f25121_Cfunc_puts _cgo_be59f0f25121_Cfunc_puts 671 var __cgofn__cgo_be59f0f25121_Cfunc_puts byte 672 var _cgo_be59f0f25121_Cfunc_puts = unsafe.Pointer(&__cgofn__cgo_be59f0f25121_Cfunc_puts) 673 674 func _Cfunc_puts(p0 *_Ctype_char) (r1 _Ctype_int) { 675 _cgo_runtime_cgocall(_cgo_be59f0f25121_Cfunc_puts, uintptr(unsafe.Pointer(&p0))) 676 return 677 } 678 679 The hexadecimal number is a hash of cgo's input, chosen to be 680 deterministic yet unlikely to collide with other uses. The actual 681 function _cgo_be59f0f25121_Cfunc_puts is implemented in a C source 682 file compiled by gcc, the file x.cgo2.c: 683 684 void 685 _cgo_be59f0f25121_Cfunc_puts(void *v) 686 { 687 struct { 688 char* p0; 689 int r; 690 char __pad12[4]; 691 } __attribute__((__packed__, __gcc_struct__)) *a = v; 692 a->r = puts((void*)a->p0); 693 } 694 695 It extracts the arguments from the pointer to _Cfunc_puts's argument 696 frame, invokes the system C function (in this case, puts), stores the 697 result in the frame, and returns. 698 699 Linking 700 701 Once the _cgo_export.c and *.cgo2.c files have been compiled with gcc, 702 they need to be linked into the final binary, along with the libraries 703 they might depend on (in the case of puts, stdio). cmd/link has been 704 extended to understand basic ELF files, but it does not understand ELF 705 in the full complexity that modern C libraries embrace, so it cannot 706 in general generate direct references to the system libraries. 707 708 Instead, the build process generates an object file using dynamic 709 linkage to the desired libraries. The main function is provided by 710 _cgo_main.c: 711 712 int main() { return 0; } 713 void crosscall2(void(*fn)(void*, int, uintptr_t), void *a, int c, uintptr_t ctxt) { } 714 uintptr_t _cgo_wait_runtime_init_done() { return 0; } 715 void _cgo_release_context(uintptr_t ctxt) { } 716 char* _cgo_topofstack(void) { return (char*)0; } 717 void _cgo_allocate(void *a, int c) { } 718 void _cgo_panic(void *a, int c) { } 719 void _cgo_reginit(void) { } 720 721 The extra functions here are stubs to satisfy the references in the C 722 code generated for gcc. The build process links this stub, along with 723 _cgo_export.c and *.cgo2.c, into a dynamic executable and then lets 724 cgo examine the executable. Cgo records the list of shared library 725 references and resolved names and writes them into a new file 726 _cgo_import.go, which looks like: 727 728 //go:cgo_dynamic_linker "/lib64/ld-linux-x86-64.so.2" 729 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6" 730 //go:cgo_import_dynamic __libc_start_main __libc_start_main#GLIBC_2.2.5 "libc.so.6" 731 //go:cgo_import_dynamic stdout stdout#GLIBC_2.2.5 "libc.so.6" 732 //go:cgo_import_dynamic fflush fflush#GLIBC_2.2.5 "libc.so.6" 733 //go:cgo_import_dynamic _ _ "libpthread.so.0" 734 //go:cgo_import_dynamic _ _ "libc.so.6" 735 736 In the end, the compiled Go package, which will eventually be 737 presented to cmd/link as part of a larger program, contains: 738 739 _go_.o # gc-compiled object for _cgo_gotypes.go, _cgo_import.go, *.cgo1.go 740 _all.o # gcc-compiled object for _cgo_export.c, *.cgo2.c 741 742 The final program will be a dynamic executable, so that cmd/link can avoid 743 needing to process arbitrary .o files. It only needs to process the .o 744 files generated from C files that cgo writes, and those are much more 745 limited in the ELF or other features that they use. 746 747 In essence, the _cgo_import.o file includes the extra linking 748 directives that cmd/link is not sophisticated enough to derive from _all.o 749 on its own. Similarly, the _all.o uses dynamic references to real 750 system object code because cmd/link is not sophisticated enough to process 751 the real code. 752 753 The main benefits of this system are that cmd/link remains relatively simple 754 (it does not need to implement a complete ELF and Mach-O linker) and 755 that gcc is not needed after the package is compiled. For example, 756 package net uses cgo for access to name resolution functions provided 757 by libc. Although gcc is needed to compile package net, gcc is not 758 needed to link programs that import package net. 759 760 Runtime 761 762 When using cgo, Go must not assume that it owns all details of the 763 process. In particular it needs to coordinate with C in the use of 764 threads and thread-local storage. The runtime package declares a few 765 variables: 766 767 var ( 768 iscgo bool 769 _cgo_init unsafe.Pointer 770 _cgo_thread_start unsafe.Pointer 771 ) 772 773 Any package using cgo imports "runtime/cgo", which provides 774 initializations for these variables. It sets iscgo to true, _cgo_init 775 to a gcc-compiled function that can be called early during program 776 startup, and _cgo_thread_start to a gcc-compiled function that can be 777 used to create a new thread, in place of the runtime's usual direct 778 system calls. 779 780 Internal and External Linking 781 782 The text above describes "internal" linking, in which cmd/link parses and 783 links host object files (ELF, Mach-O, PE, and so on) into the final 784 executable itself. Keeping cmd/link simple means we cannot possibly 785 implement the full semantics of the host linker, so the kinds of 786 objects that can be linked directly into the binary is limited (other 787 code can only be used as a dynamic library). On the other hand, when 788 using internal linking, cmd/link can generate Go binaries by itself. 789 790 In order to allow linking arbitrary object files without requiring 791 dynamic libraries, cgo supports an "external" linking mode too. In 792 external linking mode, cmd/link does not process any host object files. 793 Instead, it collects all the Go code and writes a single go.o object 794 file containing it. Then it invokes the host linker (usually gcc) to 795 combine the go.o object file and any supporting non-Go code into a 796 final executable. External linking avoids the dynamic library 797 requirement but introduces a requirement that the host linker be 798 present to create such a binary. 799 800 Most builds both compile source code and invoke the linker to create a 801 binary. When cgo is involved, the compile step already requires gcc, so 802 it is not problematic for the link step to require gcc too. 803 804 An important exception is builds using a pre-compiled copy of the 805 standard library. In particular, package net uses cgo on most systems, 806 and we want to preserve the ability to compile pure Go code that 807 imports net without requiring gcc to be present at link time. (In this 808 case, the dynamic library requirement is less significant, because the 809 only library involved is libc.so, which can usually be assumed 810 present.) 811 812 This conflict between functionality and the gcc requirement means we 813 must support both internal and external linking, depending on the 814 circumstances: if net is the only cgo-using package, then internal 815 linking is probably fine, but if other packages are involved, so that there 816 are dependencies on libraries beyond libc, external linking is likely 817 to work better. The compilation of a package records the relevant 818 information to support both linking modes, leaving the decision 819 to be made when linking the final binary. 820 821 Linking Directives 822 823 In either linking mode, package-specific directives must be passed 824 through to cmd/link. These are communicated by writing //go: directives in a 825 Go source file compiled by gc. The directives are copied into the .o 826 object file and then processed by the linker. 827 828 The directives are: 829 830 //go:cgo_import_dynamic <local> [<remote> ["<library>"]] 831 832 In internal linking mode, allow an unresolved reference to 833 <local>, assuming it will be resolved by a dynamic library 834 symbol. The optional <remote> specifies the symbol's name and 835 possibly version in the dynamic library, and the optional "<library>" 836 names the specific library where the symbol should be found. 837 838 In the <remote>, # or @ can be used to introduce a symbol version. 839 840 Examples: 841 //go:cgo_import_dynamic puts 842 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5 843 //go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6" 844 845 A side effect of the cgo_import_dynamic directive with a 846 library is to make the final binary depend on that dynamic 847 library. To get the dependency without importing any specific 848 symbols, use _ for local and remote. 849 850 Example: 851 //go:cgo_import_dynamic _ _ "libc.so.6" 852 853 For compatibility with current versions of SWIG, 854 #pragma dynimport is an alias for //go:cgo_import_dynamic. 855 856 //go:cgo_dynamic_linker "<path>" 857 858 In internal linking mode, use "<path>" as the dynamic linker 859 in the final binary. This directive is only needed from one 860 package when constructing a binary; by convention it is 861 supplied by runtime/cgo. 862 863 Example: 864 //go:cgo_dynamic_linker "/lib/ld-linux.so.2" 865 866 //go:cgo_export_dynamic <local> <remote> 867 868 In internal linking mode, put the Go symbol 869 named <local> into the program's exported symbol table as 870 <remote>, so that C code can refer to it by that name. This 871 mechanism makes it possible for C code to call back into Go or 872 to share Go's data. 873 874 For compatibility with current versions of SWIG, 875 #pragma dynexport is an alias for //go:cgo_export_dynamic. 876 877 //go:cgo_import_static <local> 878 879 In external linking mode, allow unresolved references to 880 <local> in the go.o object file prepared for the host linker, 881 under the assumption that <local> will be supplied by the 882 other object files that will be linked with go.o. 883 884 Example: 885 //go:cgo_import_static puts_wrapper 886 887 //go:cgo_export_static <local> <remote> 888 889 In external linking mode, put the Go symbol 890 named <local> into the program's exported symbol table as 891 <remote>, so that C code can refer to it by that name. This 892 mechanism makes it possible for C code to call back into Go or 893 to share Go's data. 894 895 //go:cgo_ldflag "<arg>" 896 897 In external linking mode, invoke the host linker (usually gcc) 898 with "<arg>" as a command-line argument following the .o files. 899 Note that the arguments are for "gcc", not "ld". 900 901 Example: 902 //go:cgo_ldflag "-lpthread" 903 //go:cgo_ldflag "-L/usr/local/sqlite3/lib" 904 905 A package compiled with cgo will include directives for both 906 internal and external linking; the linker will select the appropriate 907 subset for the chosen linking mode. 908 909 Example 910 911 As a simple example, consider a package that uses cgo to call C.sin. 912 The following code will be generated by cgo: 913 914 // compiled by gc 915 916 //go:cgo_ldflag "-lm" 917 918 type _Ctype_double float64 919 920 //go:cgo_import_static _cgo_gcc_Cfunc_sin 921 //go:linkname __cgo_gcc_Cfunc_sin _cgo_gcc_Cfunc_sin 922 var __cgo_gcc_Cfunc_sin byte 923 var _cgo_gcc_Cfunc_sin = unsafe.Pointer(&__cgo_gcc_Cfunc_sin) 924 925 func _Cfunc_sin(p0 _Ctype_double) (r1 _Ctype_double) { 926 _cgo_runtime_cgocall(_cgo_gcc_Cfunc_sin, uintptr(unsafe.Pointer(&p0))) 927 return 928 } 929 930 // compiled by gcc, into foo.cgo2.o 931 932 void 933 _cgo_gcc_Cfunc_sin(void *v) 934 { 935 struct { 936 double p0; 937 double r; 938 } __attribute__((__packed__)) *a = v; 939 a->r = sin(a->p0); 940 } 941 942 What happens at link time depends on whether the final binary is linked 943 using the internal or external mode. If other packages are compiled in 944 "external only" mode, then the final link will be an external one. 945 Otherwise the link will be an internal one. 946 947 The linking directives are used according to the kind of final link 948 used. 949 950 In internal mode, cmd/link itself processes all the host object files, in 951 particular foo.cgo2.o. To do so, it uses the cgo_import_dynamic and 952 cgo_dynamic_linker directives to learn that the otherwise undefined 953 reference to sin in foo.cgo2.o should be rewritten to refer to the 954 symbol sin with version GLIBC_2.2.5 from the dynamic library 955 "libm.so.6", and the binary should request "/lib/ld-linux.so.2" as its 956 runtime dynamic linker. 957 958 In external mode, cmd/link does not process any host object files, in 959 particular foo.cgo2.o. It links together the gc-generated object 960 files, along with any other Go code, into a go.o file. While doing 961 that, cmd/link will discover that there is no definition for 962 _cgo_gcc_Cfunc_sin, referred to by the gc-compiled source file. This 963 is okay, because cmd/link also processes the cgo_import_static directive and 964 knows that _cgo_gcc_Cfunc_sin is expected to be supplied by a host 965 object file, so cmd/link does not treat the missing symbol as an error when 966 creating go.o. Indeed, the definition for _cgo_gcc_Cfunc_sin will be 967 provided to the host linker by foo2.cgo.o, which in turn will need the 968 symbol 'sin'. cmd/link also processes the cgo_ldflag directives, so that it 969 knows that the eventual host link command must include the -lm 970 argument, so that the host linker will be able to find 'sin' in the 971 math library. 972 973 cmd/link Command Line Interface 974 975 The go command and any other Go-aware build systems invoke cmd/link 976 to link a collection of packages into a single binary. By default, cmd/link will 977 present the same interface it does today: 978 979 cmd/link main.a 980 981 produces a file named a.out, even if cmd/link does so by invoking the host 982 linker in external linking mode. 983 984 By default, cmd/link will decide the linking mode as follows: if the only 985 packages using cgo are those on a whitelist of standard library 986 packages (net, os/user, runtime/cgo), cmd/link will use internal linking 987 mode. Otherwise, there are non-standard cgo packages involved, and cmd/link 988 will use external linking mode. The first rule means that a build of 989 the godoc binary, which uses net but no other cgo, can run without 990 needing gcc available. The second rule means that a build of a 991 cgo-wrapped library like sqlite3 can generate a standalone executable 992 instead of needing to refer to a dynamic library. The specific choice 993 can be overridden using a command line flag: cmd/link -linkmode=internal or 994 cmd/link -linkmode=external. 995 996 In an external link, cmd/link will create a temporary directory, write any 997 host object files found in package archives to that directory (renamed 998 to avoid conflicts), write the go.o file to that directory, and invoke 999 the host linker. The default value for the host linker is $CC, split 1000 into fields, or else "gcc". The specific host linker command line can 1001 be overridden using command line flags: cmd/link -extld=clang 1002 -extldflags='-ggdb -O3'. If any package in a build includes a .cc or 1003 other file compiled by the C++ compiler, the go tool will use the 1004 -extld option to set the host linker to the C++ compiler. 1005 1006 These defaults mean that Go-aware build systems can ignore the linking 1007 changes and keep running plain 'cmd/link' and get reasonable results, but 1008 they can also control the linking details if desired. 1009 1010 */