繁体   English   中英

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

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

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())
}

它工作正常:

$ go install
$ foo
forty-two == 42

但是,它自己的.c文件中的C代码:

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

...引用自Go:

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

...不起作用:

$ go install
# foo
could not determine kind of name for C.fortythree

C头文件foo.h丢失:

// foo.h
int fortythree();

像这样从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())
}

看哪,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