如何使用sqlite3.h和cgo打开新的sqlite3数据库?

I am trying to use sqlite3 through C with cgo (I know that go has a sqlite3 wrapper, but want to try this way). This program gives me an error message

(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)

, and I do not understand why - could someone help me with understanding how to open a new database stream?

// 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)

}

1个回答



“未定义符号”表示构建过程未将代码与系统上的sqlite库链接。 </ p>

将现有的go-sqlite库放置在软件包目录一个C文件,其中#include了SQLite的全部代码(在同一软件包中为lib / sqlite3.c)。 它还在sqlite3中提供了一些编译器标志(CFLAGS)和C包装函数 .go 。</ p>

该方法的方便之处在于,它意味着SQLite最终直接链接到您的二进制文件中,因此它的用户不必在之前单独安装SQLite 他们可以运行您的程序。 在 gc </ code>工具链上构建的程序(与 gccgo </ code>相对)仅使用pure-Go库,默认情况下采用这种方式,因此有点“ Go-y” </ p>

另一种方法是在外部“ C”之前的代码中使用cgo pragma #cgo LDFLAGS:-lsqlite3 </ code> </ 代码>声明; 那么用户需要安装兼容的sqlite3库才能使用您的二进制文件,但是您不需要存储库中的源代码,这可能会更容易。 请注意,使用这种方法的人想要 build </ em>您的软件包仍然需要在系统上使用SQLite标头,例如,从Linux发行版可能提供的 libsqlite3-dev </ code>软件包中。</ p>

希望这对于cgo和库集成具有一般帮助的价值。 我确实认为仅在可用时使用go-sqlite3或其他现有的包装程序可能会更好。</ p>
</ div>

展开原文

原文

"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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问