I'm absolutely new to CGo. I don't want to use mattn's go-sqlite package and would like to build my own minimal interface to SQLite.
I'm trying to get compiled the simplest program on my linux machine with go build
, and it always returns the same error:
/usr/bin/ld: $WORK/b001/_x003.o: in function `unixDlError':
./sqlite3.c:42036: undefined reference to `dlerror'
/usr/bin/ld: $WORK/b001/_x003.o: in function `unixDlClose':
./sqlite3.c:42067: undefined reference to `dlclose'
/usr/bin/ld: $WORK/b001/_x003.o: in function `unixDlSym':
./sqlite3.c:42063: undefined reference to `dlsym'
/usr/bin/ld: $WORK/b001/_x003.o: in function `unixDlOpen':
./sqlite3.c:42022: undefined reference to `dlopen'
collect2: error: ld returned 1 exit status
The project layout is:
- go.mod
- main.go
- sqlite3.c
- sqlite3.h
The contents if main.go
is:
//go:build cgo
// build cgo
package main
/*
#cgo CFLAGS: -DSQLITE_OMIT_LOAD_EXTENSION
#cgo CFLAGS: -DSQLITE_THREADSAFE=1
#include "sqlite.h"
*/
import "C"
func main() {
}
I'm using Go 1.18.1.
Any help or nudge in the right direction is greatly appreciated!
CodePudding user response:
To embed some C code inside a Go file, you write the C statements as something called preambles. There are certain strict rules regarding the formatting:
import "C"
is a standalone statement, and cannot be included in animport ()
group- The C includes and other code (preambles) immediately precede the
import "C"
statement, without any blank lines in between
So in your case, what you need is something like:
package main
// #include "sqlite.h"
import "C"
import (
"fmt"
// normal imports here
)
As you have since verified: preambles can be multi-line comments, so use whichever you prefer. The main thing is that there is no blank lines between them and the import "C"
statement.