使用外部实现将模板编译为静态库

Compile Templates with External Implementation to Static Library

本文关键字:编译 静态 外部 实现      更新时间:2023-10-16

我有一些类,我正在尝试编译为外部静态库。我的 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 文件。我做错了什么?我想创建一个可移植库,我可以从此代码将其放入现有项目中。

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

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

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