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