Question

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)

}

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top