dqyknf4423
2017-12-10 07:17
浏览 320
已采纳

Linux上的Golang C共享-ld找不到-ltest

I'm trying to follow the instructions in http://snowsyn.net/2016/09/11/creating-shared-libraries-in-go/

My project is somewhat simpler. The library has one test function with println. As the title says, I'm getting 'cannot find'.

I'm running Ubuntu zesty and go 1.7.4

ls -l

roy@roy-desktop:~/go/src/c$ ls -l total 2016 -rw-rw-r-- 1 roy roy 43 Dec 10 06:55 test.c -rw-rw-r-- 1 roy roy 1274 Dec 10 06:54 test.h -rw-rw-r-- 1 roy roy 2053664 Dec 10 06:54 test.so

test.c

#include "test.h"

int main() {
    test();
}

lib.go

package main

import "fmt"
import "C"


//export test
func test() {
    fmt.Println("test")
}

func main() {}

test.h and test.so were generated with: go build -o test.so -buildmode=c-shared test.go

invocation of gcc fails as follows:

roy@roy-desktop:~/go/src/c$ gcc -o test test.c -L. -ltest
/usr/bin/ld: cannot find -ltest
collect2: error: ld returned 1 exit status

The original example uses clang but googling indicates the invocation should work for gcc as well.

Post Solution

A couple of extra comments:

  1. A function name in go func test() {} will appear in nm as _test but should be declared in C as extern void test();

  2. For some reason, the invocation go build -buildmode=c-shared does not generate a header file on OSX but does on Linux.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试遵循”> http://snowsyn.net/2016/09/11/creating-shared-libraries-in-go/

我的项目比较简单。 该库对println具有一项测试功能。 就像标题中所说的,我正在'找不到'。

我正在运行Ubuntu zesty并运行1.7.4

ls -l

roy @ roy-desktop:〜/ go / src / c $ ls -l 总计2016 -rw-rw-r-- 1 roy roy 10年12月43日 06:55 test.c -rw-rw-r-- 1 roy roy 1274 Dec 10 06:54 test.h -rw-rw-r-- 1 roy roy 2053664 Dec 10 06:54 test.so

test.c

  #include“ test.h” 
 
int main(){
测试 (); 
} 
   
 
 

lib.go

 包main 
 
import“ fmt” \  nimport“ C” 
 
 
 //导出测试
func test(){
 fmt.Println(“ test”)
} 
 
func main(){} 
   
 
 

test.h和test.so的生成方式如下:go build -o test.so -buildmode = c-shared test.go

调用gcc 失败如下:

  roy @ roy-desktop:〜/ go / src / c $ gcc -o test test.c -L。  -ltest 
 / usr / bin / ld:找不到-ltest 
collect2:错误:ld返回1退出状态
   
 
 

原始示例使用clang但谷歌搜索指示

发布解决方案

一些额外的注释:

  1. go func test(){} 中的函数名称将在nm中显示为 _test ,但应在C中声明为 extern void test();

  2. 由于某种原因,调用 go build -buildmode = c-shared 不会生成 头文件在OSX上,但是在Linux上。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题