Question

I try to write a wrapper class for leveldb. Basically the part of the header file which generates my problem is (CLevelDBStore.h:)

#include "leveldb/db.h"
#include "leveldb/comparator.h"

using namespace leveldb;
class CLevelDBStore {

    public:
        CLevelDBStore(const char* dbFileName);
        virtual              ~CLevelDBStore();

        /* more stuff */ 67 private:

    private:
        CLevelDBStore();
        static               leveldb::DB* ldb_;
};

The corresponding code in the CLevelDBStore.cpp file is:

#include "CLevelDBStore.h"
DB* CLevelDBStore::ldb_;

CLevelDBStore::CLevelDBStore(const char* dbFileName) {
    Options options;
    options.create_if_missing = true;

    DB::Open((const Options&)options, (const std::string&) dbFileName, (DB**)&ldb_);
    Status status = DB::Open(options, dbFileName);
}

I now try to compile my test file (test.cpp), which basically is

#include "leveldb/db.h"
#include "leveldb/comparator.h"
#include "CLevelDBStore.h"

int main() {
    std::cout << "does not compile" << std::endl;
    return 0;
}

Note, I don't even use the wrapper class yet. It's just to generate the compilation error.

The compilation

g++ -Wall -O0 -ggdb -c CLevelDBStore.cpp -I/path/to/leveldb/include
g++ -Wall test.cpp -O0 -ggdb -L/path/to/leveldb -I/path/to/leveldb/include \
   -lleveldb -Wall -O2   -lz -lpthread ./CLevelDBStore.o -llog4cxx \
   -o levelDBStoretest

yields

CLevelDBStore.cpp:27: undefined reference to `leveldb::DB::Open(leveldb::Options const&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, leveldb::DB**)'

I looked at the leveldb code where leveldb::DB::Open is defined and it turned out to be a static method.

class DB {
    public:
        static Status Open(const Options& options,
                           const std::string& name,
                           DB** dbptr);
    /* much more stuff */
}

Could this somehow generated problemes when linking?

Was it helpful?

Solution

I think this is library link order. Try placing -leveldb after CLevelDBStore.o:

g++ -Wall test.cpp -O0 -ggdb -L/path/to/leveldb -I/path/to/leveldb/include -Wall -O2 ./CLevelDBStore.o -lleveldb -lz -lpthread -llog4cxx -o levelDBStoretest

From GCC Options for Linking:

-llibrary

Search the library named library when linking. It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o' searches libraryz' after file foo.o but before bar.o. If bar.o refers to functions in `z', those functions may not be loaded.

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