Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use external .c files with CGO?

Tags:

c

import

go

cgo

To write some C code in a comment above import "C" is straightforward:

// foo.go
package main

/*
int fortytwo() {
    return 42;
}
*/
import "C"
import "fmt"

func main() {
    fmt.Printf("forty-two == %d\n", C.fortytwo())
    fmt.Printf("forty-three == %d\n", C.fortythree())
}

And it works fine:

$ go install
$ foo
forty-two == 42

However, C code in it's own .c file:

// foo.c
int fortythree() {
  return 43;
}

...referenced from Go:

// foo.go
func main() {
    fmt.Printf("forty-two == %d\n", C.fortytwo())
    fmt.Printf("forty-three == %d\n", C.fortythree())
}

...does not work:

$ go install
# foo
could not determine kind of name for C.fortythree
like image 462
Jacob Marble Avatar asked Sep 08 '25 12:09

Jacob Marble


1 Answers

The C header file foo.h is missing:

// foo.h
int fortythree();

Reference the header file from Go like this:

// foo.go
package main

/*
#include "foo.h"

int fortytwo() {
    return 42;
}
*/
import "C"
import "fmt"

func main() {
    fmt.Printf("forty-two == %d\n", C.fortytwo())
    fmt.Printf("forty-three == %d\n", C.fortythree())
}

Behold, the power of foo.h:

$ go install
$ foo
forty-two == 42
forty-three == 43
like image 145
Jacob Marble Avatar answered Sep 11 '25 02:09

Jacob Marble