When are header-only libraries acceptable?

前端 未结 4 1957
陌清茗
陌清茗 2020-12-14 01:30

Personally, I quite like header-only libraries, but there are claims they cause code bloat due to over-inlining (as well as the other obvious problem of longer compile times

4条回答
  •  鱼传尺愫
    2020-12-14 01:54

    I agree, inline libraries are much easier to consume.

    Inline bloat mostly depends on the development platform you are working with - specifically, on the compiler / linker capabilities. I wouldn't expect it to be a major problem wiht VC9 except in a few corner cases.

    I've seen some notable change in final size in some places of a large VC6 project, but it's hard to give a specific "acceptable, if...". You probalby need to try with your code in your devenv.

    A second problem may be compile times, even when using precompiled header (there are tradeoffs, too).

    Third, some constructs are problematic - e.g. static data members shared across translation units - or avoiding having a separate instance in each translation unit.


    I have seen the following mechanism to give the user a choice:

    // foo.h
    #ifdef MYLIB_USE_INLINE_HEADER
    #define MYLIB_INLINE inline
    #else 
    #define MYLIB_INLINE 
    #endif
    
    void Foo();  // a gazillion of declarations
    
    #ifdef MYLIB_USE_INLINE_HEADER
    #include "foo.cpp"
    #endif
    
    // foo.cpp
    #include "foo.h"
    MYLIB_INLINE void Foo() { ... }
    

提交回复
热议问题