简体   繁体   English

如何在CGO中使用外部.c文件?

[英]How to use external .c files with CGO?

To write some C code in a comment above import "C" is straightforward: import "C"上方的注释中编写一些C代码很简单:

// 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: 但是,它自己的.c文件中的C代码:

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

...referenced from Go: ...引用自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

The C header file foo.h is missing: C头文件foo.h丢失:

// foo.h
int fortythree();

Reference the header file from Go like this: 像这样从Go引用头文件:

// 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: 看哪,foo.h的力量:

$ go install
$ foo
forty-two == 42
forty-three == 43

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM