我什么时候应该考虑使库仅标头? [英] When should I consider making a library header-only?

查看:153
本文介绍了我什么时候应该考虑使库仅标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然模板库只需要是标头,但是对于非模板,什么时候应该使它们只标头呢?

Obviously template libraries need to be header only, but for non-templates, when should you make things header-only?

推荐答案

如果您认为非模板库可能仅是标头,请考虑将其分为两个文件,然后提供第三个文件,该文件同时包含.cpp(带有包含保护).

If you think your non-template library could be header-only, consider dividing it into two files anyway, then providing a third file that includes both the .h and the .cpp (with an include guard).

然后,在许多不同的TU中使用您的库的任何人,如果怀疑这可能会花费大量的编译时间,就可以轻松进行更改以对其进行测试.

Then anyone who uses your library in a lot of different TUs, and suspects that this might be costing a lot of compile time, can easily make the change to test it.

一旦您知道用户可以选择哪种方式使用该库,答案就可能变成尽可能提供该选项".几乎任何时候,从多个TU包含它都不会违反ODR.例如,如果您的非static自由函数引用了static全局变量,那么您就不走运了,因为该函数在不同TU中的不同定义将引用相同名称的不同对象,这是违反ODR.

Once you know users have the option which way to use the library, the answer probably becomes "offer that option whenever you possibly can". So pretty much any time that including it from multiple TUs wouldn't violate the ODR. For instance, if your non-static free functions refer to static globals, then you're out of luck, since the different definitions of that function in different TUs would refer to different objects by the same name, which is an ODR-violation.

这篇关于我什么时候应该考虑使库仅标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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