共享库中未使用的模板函数

xyz*_*yzt 2 c++ templates

我在用C++编写的共享库中有一个模板函数(该函数不在库中的任何地方调用,所以不应该生成它,我错了吗?)[g ++,Linux]

我尝试在应用程序中使用此模板函数,但编译器给出链接错误.我使用objdump搜索函数但我无法在.so中看到函数有没有办法解决这个问题?

Mat*_*gro 7

模板函数属于库头,它们不在DLL共享库中编译.因此,将所有模板函数移动到标题中,并在应用程序中包含该标题.

  • @xyzt:这对Linux也有效. (2认同)

Mar*_*ork 6

最简单的方法就是将所有的模板代码放到头文件(在其他的答案中描述)
,这不是唯一的解决办法.

模板不是实际功能.

当存在函数的实例化时,模板成为函数.这可以隐式或明确地完成.无论何时使用该函数,都存在隐式实例.但您也可以明确地实现模板功能.

因此,您应该能够链接到共享库中任何实例化的模板函数版本.

头文件所以我们遵守一个定义规则.

// tt.h
template<typename T>
int doStuff(Tconst &t);
Run Code Online (Sandbox Code Playgroud)

源文件:

// tt.cpp
#include "tt.h"
template<typename T>
int doStuff(Tconst &t)
{
    return 4;
}

void plop()
{
    int x = 6;
    // implicit instanciation of doStuff<int>(int const&);
    doStuff(x);
}

// explicit instanciation of template
template int doStuff<float>(float const&);
Run Code Online (Sandbox Code Playgroud)

如果我将上面的内容编译成共享库.
然后会有两个可用的doStuff()方法.

  • doStuff <int>(int const&)//隐式实例化
  • doStuff <float>(float const&)// explit instanciation

g ++ -shared -o tt.so tt.cpp

现在,如果我们有一个seprate文件,我们链接到共享库:

// main.cpp
#include "tt.h"

int main()
{
    doStuff(5);   // doStuff<int>()
    doStuff(6.0f); // doStuff<float>()
}
Run Code Online (Sandbox Code Playgroud)

g ++ main.cpp t.so

即使main看不到任何模板代码,编译也很好.