如何创建仅标头的库? [英] How do I create a header-only library?

查看:167
本文介绍了如何创建仅标头的库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将正在使用的库打包为仅标头的库,以使客户端更易于使用. (它很小,实际上没有理由将其放在单独的翻译单元中).但是,我不能简单地将代码放在标头中,因为这违反了C ++的一个定义规则. (假设库头包含在一个客户项目的多个翻译单元中)

I'd like to package a library I'm working on as a header-only library to make it easier for clients to use. (It's small and there's really no reason to put it into a separate translation unit) However, I cannot simply put my code in headers because this violates C++'s one definition rule. (Assuming that the library header is included in multiple translation units of a client project)

一个人如何修改一个库以使其仅标头?

How does one modify a library to make it header-only?

推荐答案

您可以使用inline关键字:

// header.hpp (included into multiple translation units)

void foo_bad() {} // multiple definitions, one in every translation unit :(

inline void foo_good() {} // ok :)

inline允许链接程序简单地选择一个定义,并丢弃其余的定义.

inline allows the linker to simply pick one definition and discard the rest.

(因此,如果这些定义实际上不匹配,则会产生很多未定义的行为...!)

(As such, if those definitions don't actually match, you get a good dose of undefined behavior...!)

顺便说一句,在类类型中定义的成员函数被隐式标记为inline:

As an aside, member functions defined within a class-type, are implicitly marked inline:

struct myclass
{
    void i_am_inline_implicitly()
    {
        // because my definition is here
    }

    void but_i_am_not();
    void neither_am_i();
};

inline void myclass::but_i_am_not()
{
    // but that doesn't mean my definition cannot be explicitly inline
}

void myclass::neither_am_i()
{
    // but in this case, no inline for me :(
}

这篇关于如何创建仅标头的库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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