我正在尝试在 main.c 文件中使用 sqlite 库:
#include <stdio.h>
#include "sqlite3.h"
int main() {
printf("%s\n", sqlite3_libversion());
return 0;
}
但是我收到以下错误:
CMakeFiles\Database.dir/objects.a(main.c.obj): In function `main':
C:/Users/Andrea/Desktop/Database/main.c:7: undefined reference to `sqlite3_libversion'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\Database.dir\build.make:104: Database.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:94: CMakeFiles/Database.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:101: CMakeFiles/Database.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:136: Database] Error 2
我从官网下载了sqlite3.h文件,并将其放在main.c文件同一个文件夹中。 这是 CMakeList.txt:
cmake_minimum_required(VERSION 3.19)
project(Database C)
set(CMAKE_C_STANDARD 11)
add_executable(Database main.c sqlite3.h)
请帮我修改CMakeList.txt文件以便可以编译代码吗?
您要做的就是从这个网站下载almagation源代码:almagation。它有您需要的所有 c 文件。解压后就可以这样使用了:
#include <stdlib.h>
#include <stdio.h>
//sqlite-...0000\ is the default folder name
//You should store this folder in the same folder with your c file
#include "sqlite-amalgamation-3420000\sqlite3.c"
#include "sqlite-amalgamation-3420000\sqlite3.h"
static int callback(void *data, int argc, char **argv, char **azColName);
int main(int argc , char ** argv){
sqlite3 *db; //The data base pointer
char *dbErr = 0; //Use this to store the errors when using sql_exec()
int rc; //Store the result of the functions you call
rc = sqlite3_open("test.db", &db); //Open the data base
rc = sqlite3_exec(
db,
"INSERT INTO PARTALI "\
"VALUES "\
"(1,'NIKOS', 23, 'NES KAFES', 200 ), "\
"(2,'PAVLOS ', 55, 'FRAPES', 100 ), "\
"(3,'ANTONIA-MEROPI', 23, 'Nespresso', 123 ), "\
"(4,'kira', 12, 'frappes', 444 ); "
, callback //callback function (using only the name means that you pass the address of the function)
, 0 //data
, &dbErr //error message address
);
rc = sqlite3_exec(
db,
"SELECT * FROM PARTALI; "\
" "\
" "\
" "\
" "\
" "
, callback //callback function
, 0 //data passed to callback function
, &dbErr //error message address
);
//You can use this function in order to get messeges from
//each sql command you execute
fprintf(stderr, "sqlite3_errmsg %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return 0;
}
//Callback function ( it is passed with the name of the function. The name of
//the function is the address ).
//data : data that can be used in the callback function
//arg c : number of columns
//argv : field names
//colname : column names
static int callback(void *data, int argc, char **argv, char **azColName){
for(
int i = 0;
i<argc;
i++
){
printf(
"%s = %s\n",
azColName[i],
argv[i] ? argv[i] : "NULL"
);
}
printf("\n");
return 0;
}
我希望这有帮助!