Calling C Function From Go

suggest change

Cgo enables Go packages that call C code. To use cgo, write normal Go code that imports the pseudo-package "C". The Go code can then refer to types such as C.int, or functions such as C.Add. The import of "C" must be immediately preceded by a comment. That comment, called the preamble, is compiled as a header for the C parts of the package. There must be no blank lines between the cgo comment and the import statement. import "C" cannot be grouped with other imports in a parenthesized import statement. Write it as its own import:

import "C"
import "fmt"

And it is good style to use the factored import statement, for other imports, like:

import "C"
import (
    "fmt"
    "math"
)

Simple example using cgo:

package main

//int Add(int a, int b){
//    return a+b;
//}
import "C"
import "fmt"

func main() {
    a := C.int(10)
    b := C.int(20)
    c := C.Add(a, b)
    fmt.Println(c) // 30
}

Then go build, and run it, output:

30

To build cgo packages, just use go build or go install as usual. The go tool recognizes the special "C" import and automatically uses cgo for those files.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents