C++ One Header Multiple Sources

前端 未结 4 878
时光说笑
时光说笑 2021-02-19 22:35

I have a large class Foo1:

class Foo {
public:
    void apples1();
    void apples2();
    void apples3();

    void oranges1();
    void         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 23:09

    Are there any major design flaws to keeping the definition of the class in foo.h and splitting the implementation of the functions into foo_apples.cpp and foo_oranges.cpp.

    to pick nits: Are there any major design flaws to keeping the declaration of the class in foo.h and splitting the definitions of the methods into foo_apples.cpp and foo_oranges.cpp.

    1) apples and oranges may use the same private programs. an example of this would be implementation found in an anonymous namespace.

    in that case, one requirement would be to ensure your static data is not multiply defined. inline functions are not really a problem if they do not use static data (although their definitions may be multiply exported).

    to overcome those problems, you may then be inclined to utilise storage in the class -- which could introduce dependencies by increasing of data/types which would have otherwise been hidden. in either event, it can increase complexity or force you to write your program differently.

    2) it increases complexity of static initialization.

    3) it increases compile times

    the alternative i use (which btw many devs detest) in really large programs is to create a collection of exported local headers. these headers are visible only to the package/library. in your example, it can be illustrated by creating the following headers: Foo.static.exported.hpp (if needed) + Foo.private.exported.hpp (if needed) + Foo.apples.exported.hpp + Foo.oranges.exported.hpp.

    then you would write Foo.cpp like so:

    #include "DEPENDENCIES.hpp"
    #include "Foo.static.exported.hpp" /* if needed */
    #include "Foo.private.exported.hpp" /* if needed */
    #include "Foo.apples.exported.hpp"
    #include "Foo.oranges.exported.hpp"
    
    /* no definitions here */
    

    you can easily adjust how those files are divided based on your needs. if you write your programs using c++ conventions, there are rarely collisions across huge TUs. if you write like a C programmer (lots of globals, preprocessor abuse, low warning levels and free declarations), then this approach will expose a lot of issues you probably won't care to correct.

提交回复
热议问题