1

我正在尝试通过 C 将 sqlite3 与 cgo 一起使用(我知道 go 有一个 sqlite3 包装器,但想尝试这种方式)。这个程序给了我一个错误信息

(Undefined symbols for architecture x86_64:
"_sqlite3_open", referenced from:
  __cgo_1d4838eae1de_Cfunc_sqlite3_open in cGo.cgo2.o
 (maybe you meant: __cgo_1d4838eae1de_Cfunc_sqlite3_open)
 ld: symbol(s) not found for architecture x86_64
 clang: error: linker command failed with exit code 1 (use -v to see invocation)

,我不明白为什么-有人可以帮助我了解如何打开新的数据库流吗?

// cGo
package main

/*
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
*/
import  "C"
//import "fmt"


func main() {
var t* C.sqlite3
C.sqlite3_open("test.db", t)

}

4

1 回答 1

3

"Undefined symbol" means that the build process isn't linking your code with the sqlite library on your system.

The existing go-sqlite library gets linked to SQLite by placing in the package directory a C file which #include's the whole code of SQLite (lib/sqlite3.c in the same package). It also provides some compiler flags (CFLAGS) and C wrapper functions in sqlite3.go.

The handy thing about that approach is that it means SQLite ends up linked right into your binary, so users of it don't have to separately install SQLite before they can run your program. Programs built on the gc toolchain (as opposed to gccgo) that use only pure-Go libraries are this way by default, so it's kind of "Go-y" to do it that way.

Another approach is to use the cgo pragma #cgo LDFLAGS: -lsqlite3 in the code before your extern "C" declaration; then users need a compatible sqlite3 library installed to use your binary, but you don't need the source in your repository and it might be easier. Note that with this approach folks who want to build your package still need SQLite headers on their system, e.g., from an libsqlite3-dev package their Linux distribution might provide.

Hope this has value as general help for cgo and library integration. I do think just using go-sqlite3 or another existing wrapper when available is likely to work out better.

于 2014-04-27T03:33:20.880 回答