简体   繁体   English

非模板类的显式类实例化

[英]Explicit class instantiation for non-templated classes

In C++, you can explicitly instantiate a templated class like this: 在C ++中,您可以像这样显式实例化模板化类:

template class A<B>;

This forces the compiler to include all of that class's methods its output, which is very useful for assessing which ones are covered by tests. 这迫使编译器在其输出中包括该类的所有方法,这对于评估测试覆盖哪些方法非常有用。

While (as I understand it) non-templated classes technically get instantiated automatically, unused methods of non-templated classes are often left out of the compiler's output (even with -O0 and other similar flags). 尽管(据我所知)非模板类在技术上会自动实例化,但未模板类的未使用方法通常会被排除在编译器的输出之外(即使带有-O0和其他类似的标志)。 Is there a way to force the compiler not to do that? 有没有办法强迫编译器不这样做?

There is no concept of instantiation with non template classes. 对于非模板类,没有实例化的概念。 When the compiler encounters the definition of a member function, the definition is compiled right away. 当编译器遇到成员函数的定义时,将立即编译该定义。

Whether the function is outputted in the binary is up to the compiler and your setup. 函数是否以二进制形式输出取决于编译器和您的设置。 If you compile your program as a library, all functions will be implemented. 如果将程序编译为库,则将实现所有功能。 If you use static linking, the linker won't add unused functions in you binary. 如果使用静态链接,则链接器不会在二进制文件中添加未使用的函数。

On the contrary, if you use dynamic linking, all exported definition will be there. 相反,如果使用动态链接,则所有导出的定义都将存在。 Although non exported function such as function with static linkage can be inlined without having a separated definition. 尽管可以内联非导出功能(例如具有静态链接的功能),而无需单独定义。

Whether they are actually saved and outputted into the binary is something separated from the compilation itself. 它们是否实际保存并输出到二进制文件中,与编译本身是有区别的。 For example you could instantiate 100 template functions and in reality have none outputted in the binary. 例如,您可以实例化100个模板函数,而实际上却没有二进制文件输出。 It's up to the linker if your function make it to the binary. 如果您的函数将其链接到二进制文件,则取决于链接器。

If your function is a public symbol, it will likely get into the binary. 如果您的函数是公共符号,则可能会进入二进制文件。

I didn't manage to get a solution working with dynamic linking (the reason I write header-only libraries is that I hate linkers with a firey passion), but along the way I discovered some built-in compiler options in Clang that did what I want. 我没有设法获得用于动态链接的解决方案(我之所以编写仅标头的库,是因为我讨厌对链接器怀有强烈的热情),但是在此过程中,我发现了Clang中的一些内置编译器选项,可以做到这一点我想要。 I added the -fprofile-instr-generate -fcoverage-mapping flags to my compilation, and then used llvm-profdata and llvm-cov to view the test coverage (as described here ). 我添加了-fprofile-instr-generate -fcoverage-mapping标志,以我的编译,然后使用LLVM-profdata和LLVM-COV以查看测试覆盖范围(如所描述的在这里 )。

Note for anyone else trying to make this work: make sure to use the same llvm version for all three of these commands (clang, llvm-profdata, and llvm-cov). 请注意其他要使其工作的人:请确保对所有这三个命令(clang,llvm-profdata和llvm-cov)使用相同的llvm版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM