【问题标题】:Linking static method in wrapper class for leveldb在 leveldb 的包装类中链接静态方法
【发布时间】:2012-01-23 16:50:38
【问题描述】:

我尝试为 leveldb 编写一个包装类。基本上产生我的问题的头文件部分是(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_;
};

CLevelDBStore.cpp文件中对应的代码为:

#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);
}

我现在尝试编译我的测试文件(test.cpp),基本上是

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

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

注意,我什至还没有使用包装类。只是为了产生编译错误。

编译

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

产量

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**)'

我查看了定义 leveldb::DB::Open 的 leveldb 代码,结果发现它是一个静态方法。

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

这会在链接时以某种方式产生问题吗?

【问题讨论】:

    标签: c++ static linker g++ leveldb


    【解决方案1】:

    我认为这是图书馆链接顺序。尝试将-leveldb 放在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

    来自GCC Options for Linking

    -图书馆

    链接时搜索名为 library 的库。在命令中编写此选项的位置有所不同;链接器按照指定的顺序搜索和处理库和目标文件。因此,foo.o -lz bar.o' searches libraryz' 在文件 foo.o 之后但在 bar.o 之前。如果 bar.o 引用了 `z' 中的函数,这些函数可能不会被加载。

    【讨论】:

      猜你喜欢
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      • 2014-01-17
      • 2011-12-04
      • 2012-09-04
      • 2011-01-17
      相关资源
      最近更新 更多