How to use external .c files with CGO?

huangapple go评论94阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年5月15日 00:52:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/30242905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定