在库中强制为C ++模板实例定义符号 [英] Force definition of symbol for a C++ template instance in a library

查看:132
本文介绍了在库中强制为C ++模板实例定义符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提供一个提供模板代码的库.但是,我也想尽可能地保留此代码(生成的代码)的所有权,因为我可以猜测模板通常使用的不同类型的用法.这是我要执行的操作的示例:

I'd like to provide a library that provides template code. But I would also like to keep the most possible the ownership of this code (generated code) when I can guess the usage of different usual types of my template. Here is an example of what I am trying to do:

lib1.h

#include <iostream>

template<int N>
void print_me() {
    std::cout << "I am function number " << N << std::endl;
}

lib1.cpp

#include "lib1.h"

/* Force symbols to be defined here. */
template void print_me<0>();
template void print_me<1>();

我使用以下命令编译我的库:

I compile my library using:

g ++ -shared -fPIC lib1.cpp -o lib1.so

g++ -shared -fPIC lib1.cpp -o lib1.so

当我使用我的图书馆时:

And when I use my library:

main.cpp

#include <lib1.h>

int main() {
    print_me<0>();
    print_me<1>();
    print_me<2>();
}

编译:

g ++ main.cpp -l1

g++ main.cpp -l1

在这里我希望从lib1.so中定义和使用符号print_me< 0>()和print_me< 1>()并为我的可执行文件定义和使用print_me< 2>()(检查nm-仅定义).但是似乎并非如此! 0和1的符号已在lib1.so中定义好,但为符号.并且再次在我的可执行文件(0、1和2)中重新定义,弱.这意味着我的可执行文件的0和1代码是从main.cpp中获取的,这不是我想要的(我在main.cpp中检查了规格).

Here I would expect that the symbol print_me<0>() and print_me<1>() are defined and used from lib1.so and print_me<2>() defined and used for my executable (checked with nm --defined-only). But it seems that this is not the case! The symbols for 0 and 1 are well defined in lib1.so but as weak symbols. And are redefined in my executable (0, 1 and 2) again, weak. That implies that the code for 0 and 1 for my executable is taken from main.cpp which is not what I want (I checked with specification in main.cpp).

在main.cpp的编译时是否有办法(例如在lib1.h中)说这些符号已经在某处定义了,并且不需要添加这些符号?

Is there a way (in the lib1.h for instance) to say at compile time of main.cpp that the symbols are already defined somewhere and that it does not need to add these symbols?

推荐答案

C ++ 11解决方案:使用外部模板.只需将这些字符串添加到您的main.cpp文件中:

C++11 solution: use extern templates. Simply add these strings to your main.cpp file:

extern template void print_me<0>();
extern template void print_me<1>();

因此,您告诉编译器不要在main.cpp中实例化print_me函数模板(对于模板参数0和1).因此,链接器应在其他翻译单位中搜索void print_me<0>();void print_me<1>();的定义.

Thus you tell compiler not to instantiate print_me function template in main.cpp (for template arguments 0 and 1). So linker should search definition of void print_me<0>(); and void print_me<1>(); in other translation units.

这篇关于在库中强制为C ++模板实例定义符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆