c++ - 将具有外部实现的模板编译为静态库

标签 c++ templates makefile static-libraries

我有一些类正在尝试编译为外部静态库。我的 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 都放在“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 文件,因为没有它们编译器将无法执行任何操作。

关于c++ - 将具有外部实现的模板编译为静态库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13664625/

相关文章:

c++ - 从 C/C++ 中的数据缓冲区扫描

c++ - 这个模板参数是什么意思?

c++ - 如果我们有基*类,如何访问派生模板类的成员函数

c++ - 使用 enable_if 选择特征 - 适用于 clang,但不适用于 gcc

c++ - GNU make 忽略隐式规则

c++ - 在 Tab 空间拆分 QString

c++ - 将 double* 从 c++ dll 返回到 delphi 程序

c++ - 为什么 'new' 是一个运算符,而不是一个函数?

makefile - 在一个文件夹中从不同的源文件夹创建目标文件

c - 使 `gcc' 需要 : *** No rule to make target `libmy.so' , 。停止