cgo(golang):错误:对’hello’的引用未定义。

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

cgo(golang) : error: underfined reference to 'hello'

问题

我刚刚编写了一个非常简单的演示程序,用于测试使用cgo(golang)加载共享库。代码如下:

xxx.h

#pragma once
void myprint(const char *str);

xxx.c

#include "xxx.h"
#include <stdio.h>
void myprint(const char *str) {
    printf("%s\n",str);
}

构建共享库:

gcc -fPIC -shared xxx.c -o libxxx.so

好的,从这里开始一切都正常。

现在,使用cgo加载libxxx.so,并使用myprint函数:

package main

/*
#include <stdio.h>
#cgo linux CFLAGS: -I../../include
#cgo linux LDFLAGS: -L../../lib/linux -lxxx
#include "xxx.h"
*/
import "C"

func main() {
    C.myprint(C.CString("xxx"))
}

然后,构建go演示程序:

go build test.go

正如我的标题所示:

错误:对'myprint'的引用未定义

我确保了库文件和头文件的路径是正确的,请问谁能帮我找出原因?谢谢。

英文:

I just write a very simple demo to test load the shared library with cgo(golang).the code as follow:

xxx.h

#pragma once
void myprint(const char *str);

xxx.c

#include &quot;xxx.h&quot;
#include &lt;stdio.h&gt;
void myprint(const char *str) {
    printf(&quot;%s\n&quot;,str);
}

build shared library:

gcc -fPIC -shared xxx.c -o libxxx.so

ok,everything is ok from here.

now ,use the cgo load the libxxx.so,and use the myprint function:

package main

/*
#include &lt;stdio.h&gt;
#cgo linux CFLAGS: -I../../include
#cgo linux LDFLAGS: -L../../lib/linux -lxxx
#include &quot;xxx.h&quot;
*/
import &quot;C&quot;

funct main() {
    C.myprint(C.CString(&quot;xxx&quot;))
}

then, build the go demo:

go build test.go

as my title show:

error: undefined reference to &#39;myprint&#39;

i ensure the path of lib/head file is right, Who can help me find the reason? thx.

答案1

得分: 2

相对路径在构建上下文中不起作用,因为构建发生在与源文件不同的目录中。

您有几个选择来提供绝对路径:

  • 您可以在源文件中使用绝对路径
  • 您可以使用pkg-config提供绝对路径
  • 您可以使用CGO_CFLAGSCGO_LDFLAGS环境变量
  • 您可以在源文件的#cgo行中使用${SRCDIR}变量。

有关更多详细信息,请参阅cgo文档

英文:

Relative paths don't work in the build context, because the build happens in a different directory from your source files.

You have a few choices to provide absolute paths:

  • You can use absolute paths in your source
  • You can use pkg-config to provide absolute paths
  • You can use the CGO_CFLAGS and CGO_LDFLAGS environment variables
  • You can use the ${SRCDIR} variable in the #cgo lines in your source.

See the cgo documentation for more details

huangapple
  • 本文由 发表于 2016年7月5日 19:51:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/38202761.html
匿名

发表评论

匿名网友

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

确定