我有以下使用dlopen和dlsym的代码。
main.cpp
#include <stdio.h>
#include <dlfcn.h>
int main(int argc,char** argv) {
void* handler;
handler = dlopen("./libsql.so",RTLD_LAZY);
if(handler){
int (*insert)(const char*);
char* error=NULL;
dlerror(); /* Clear any existing error */
*(void **) (&insert) = dlsym(handler, "openAndInsert");
if ((error = dlerror()) == NULL) {
(*insert)(argv[1]);
}
else {
printf("Error in dlsymn");
}
}
else {
printf("dlopen errorn");
}
return 0;
}
编译命令:g++main.cpp-ldl
libsql.cpp
#include <sqlite3.h>
#include <string.h>
#include <stdio.h>
#include "libsql.h"
int openAndInsert(const char* sql) {
sqlite3 *db;
sqlite3_stmt *stmt;
sqlite3_initialize();
int rc = sqlite3_open("./database.db", &db);
if(rc==0){
rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
if(rc==0) {
if(sqlite3_step(stmt)){
printf("Donen");
}
else {
printf("execute errorn");
}
sqlite3_finalize(stmt);
}
else {
printf("prepare errorn");
}
sqlite3_close(db);
}
else {
printf("open errorn");
}
sqlite3_shutdown();
}
libsql.h
#ifndef LIBSQL_H_
#define LIBSQL_H_
#ifdef __cplusplus
extern "C" {
#endif
int openAndInsert(const char* sql);
#ifdef __cplusplus
}
#endif
#endif
编译命令:g++-fPIC-shared-o libsql.so libsql.cpp
现在,当我运行应用程序时,我会得到如下错误。
/a.out:符号查找错误:/libsql.so:未定义的符号:sqlite3_initialize
但是libsqlite3已经安装,并且可以与其他程序配合使用。
当我使用下面的命令生成*.so文件时,它工作得很好。
g++-fPIC-共享-o libsql.so libsql.cpp-lsqlite3