如何在头文件库中定义(非方法)函数 [英] How to define (non-method) functions in header libraries

查看:74
本文介绍了如何在头文件库中定义(非方法)函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写标头库时(例如 Boost ),可以定义自由浮动(非方法))的功能,而不会(1)膨胀生成的二进制文件和(2)产生未使用"警告?

When writing a header library (like Boost), can one define free-floating (non-method) functions without (1) bloating the generated binary and (2) incurring "unused" warnings?

当我在多个源文件包含的标头中定义一个函数时,该源文件又链接到同一二进制文件中,链接器会抱怨重新定义.解决此问题的一种方法是使函数静态化,但这会在每个翻译单元中重新生成代码(BTW,链接程序可以安全地重复复制这些代码吗?).此外,这会触发编译器有关该函数未使用的警告.

When I define a function in a header that's included by multiple source files which in turn is linked into the same binary, the linker complains about redefinitions. One way around this is to make the functions static, but this reproduces the code in each translation unit (BTW, can linkers safely dereplicate these?). Furthermore, this triggers compiler warnings about the function being unused.

我试图在Boost中寻找一个自由浮动函数的示例,但找不到.将所有内容都包含在类(或模板)中的诀窍是吗?

I was trying to look for an example of a free-floating function in Boost, but I couldn't find one. Is the trick to contain everything in a class (or template)?

推荐答案

如果您确实要定义函数(而不是声明函数),则需要使用 inline 来防止链接器错误.

If you really want to define the function (as opposed to declaring it), you'll need to use inline to prevent linker errors.

否则,您可以在头文件中声明该函数,并在源文件中单独提供其实现.

Otherwise, you can declare the function in the header file and provide its implementation separately in your source file.

这篇关于如何在头文件库中定义(非方法)函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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