1

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 dlsym\n");
        }
    }
    else {
        printf("dlopen error\n");
    }
    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("Done\n");
            }
            else {
                printf("execute error\n");
            }
            sqlite3_finalize(stmt);
        }
        else {
            printf("prepare error\n");          
        }
        sqlite3_close(db);
    }
    else {
        printf("open error\n");
    }
    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 は既にインストールされており、他のプログラムで正常に動作します。

4

1 に答える 1

1

以下のコマンドを使用して *.so ファイルを生成すると、正常に動作します。

g++ -fPIC -shared -o libsql.so libsql.cpp -lsqlite3

于 2015-03-30T13:03:06.883 に答える