【问题标题】:Compile Templates with External Implementation to Static Library将具有外部实现的模板编译为静态库
【发布时间】:2012-12-01 22:59:41
【问题描述】:

我有一些类要编译为外部静态库。我的linked_list.hpp(我正在尝试编译的linked_list的标题)看起来像:

#include "list_base.hpp"

template <typename T>

class Linked_list : public List_base <T> {


    public://
        Linked_list();
        ~Linked_list();

    public://accessor functions
        Linked_list<T> * next();//go to the next element in the list
        Node<T> * get_current_node() const;//return the current node
        T get_current() const;//get the current data
        T get(int index) const;//this will get the specified index and will return the data it holds

    public://worker functions
        Linked_list<T> * push(T value);//push a value into the front of the list
        Linked_list<T> * pop_current();//deletes the current_node--resets the current as the next element in the list!
        Linked_list<T> * reset();//this resets the current to the front of the list
        Linked_list<T> * erase(int index);

    private://variables
        Node<T> * current;//store the current node


};

#include "linked_list.cpp"//grab the template implementation file


#endif

我所有的代码头都放在“header”目录中,实现放在我拥有的实现文件夹中。这些作为 -I 目录传递。

我用于编译的 make 文件命令如下所示:

static: $(DEPENDENCIES)
    ar rcs liblist_templates.a node.o list_base.o linked_list.o 

在运行时它给了我这个错误......

/usr/bin/ranlib: warning for library: liblist_templates.a the table of contents is empty (no object file members in the library define global symbols)

我创建了一个主头文件,其中包含“linked_list.hpp”和库的其他一些部分,但每当我包含它时,它似乎仍在寻找包含的 cpp 文件。我做错了什么?我想创建一个可移植的库,我可以从此代码中放入现有项目。

【问题讨论】:

    标签: c++ templates makefile static-libraries


    【解决方案1】:

    如果你的库只包含模板代码,它本身是不能编译的:例如,编译器不知道哪个类型会被用作链表中的T

    当你编译linked_list.cpp时,编译器只实现了基本的语法检查并生成了一个空的目标文件。 ranlib 然后在抱怨,因为您要求他从所有这些空目标文件中创建一个空库。

    解决方案很简单:什么都不做!您的客户端代码只需要源文件;它不需要链接到任何库。而且您总是需要发送 .cpp 文件,因为没有它们编译器将无法执行任何操作。

    【讨论】:

    • 还应注意,linked_list.cpp 需要在使用Linked_list&lt;T&gt; 的任何翻译单元中为#included。
    • 看来linked_list.cpplinked_list.hpp中已经是#included,所以客户端代码只需要包含头文件即可。
    • 哈哈——是的,没错。错过了。
    猜你喜欢
    • 2013-02-11
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 2011-07-05
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    相关资源
    最近更新 更多