首先先上代码,看看效果。
package main
/*
#include <stdio.h>
void sayHello(){
printf("hello, world!");
}
*/
import "C"
func main(){
C.sayHello()
}
如果在执行时报错exec: "gcc": executable file not found in %PATH%
,可以查看executable file not found in %PATH%的解决。
Go语言是如何设别代码中的C语言,又是如何执行的呢。这就需要了解一个工具cgo
,它是Go语言自带的特殊工具,可以使我们创建能够调用C语言代码的Go语言源码文件。在默认情况下,它是打开的。通过go env
命令可以查看它的设置情况,其中set CGO_ENABLED=1
表示cgo工具可用,当设置为0时,表示工具不可用。
上面代码中的import "C"
的作用就是为了告诉cgo工具,在这个源码文件中需要调用C代码。在该语句之前