dqg17080
2014-10-10 22:41
采纳率: 0%
浏览 76
已采纳

在Go程序中使用C代码时的未声明标识符

I am trying to use a library downloaded from the IRIS website. The makefile includes options to create dynamic and static libraries. I have tried a couple tutorials out there using both types of library with cgo and I have been unsuccessful.

Here is my go code

package main
/*
#cgo CFLAGS : -I .
#cgo LDFLAGS: -L . -llibslink
#include <libslink.h>
*/

import (
    "C"
)

func main() {

    C.sl_newslcd()

}

And I have the following files in the directory:

ChangeLog          config.o           globmatch.o        logging.c          slplatform.c       strutils.c
Makefile           doc                gswap.c            logging.o          slplatform.h       strutils.o
Makefile.wat       example            gswap.o            main.go            slplatform.o       unpack.c
Makefile.win       genutils.c         libslink.2.4.dylib msrecord.c         slutils.c          unpack.h
README             genutils.o         libslink.a         msrecord.o         slutils.o          unpack.o
README.md          globmatch.c        libslink.dylib     network.c          statefile.c
config.c           globmatch.h        libslink.h         network.o          statefile.o

My error messages are as follows on the command: go build -v main.go

command-line-arguments
# command-line-arguments
37: error: use of undeclared identifier 'SLCD'
37: error: use of undeclared identifier 'sl_newslcd'
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutang8098 2014-10-11 03:26
    已采纳

    Your main problem is that the comment is not immediately preceding the import "C" as the documentation recommends:

    If the import of "C" is immediately preceded by a comment, that comment, called the preamble, is used as a header when compiling the C parts of the package.

    So the solution is to remove the blank line between the comment and the import. This will not compile though, since for the -l parameter the lib prefix is ignored. You have to specify -lslink instead of -llibslink. At last, I recommend to have the library in some sub-folder rather than in the same directory as your .go files.

    Working example with proper sub-folder for slink:

    package main
    
    // #cgo CFLAGS: -I libslink
    // #cgo LDFLAGS: -L libslink -lslink
    // #include <libslink.h>
    import "C"
    
    func main() {
        C.sl_newslcd()
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报