英文:
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
英文:
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
答案1
得分: 8
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论