Should I put many functions into one file? Or, more or less, one function per file?

后端 未结 9 926
故里飘歌
故里飘歌 2021-01-02 02:54

I love to organize my code, so ideally I want one class per file or, when I have non-member functions, one function per file.

The reasons are:

  1. When

9条回答
  •  無奈伤痛
    2021-01-02 03:46

    One function per file has a technical advantage if you're making a static library (which I guess it's one of the reasons why projects like the Musl-libc project follow this pattern).

    Static libraries are linked with object-file granularity and so if you have a static library libfoobar.a composed of*:

     foo.o
         foo1
         foo2
     bar.o
         bar
    

    then if you link the lib for the bar function, the bar.o archive member will get linked but not the foo.o member. If you link for foo1, then the foo.o member will get linked, bringing in the possibly unnecessary foo2 function.

    There are possibly other ways of preventing unneeded functions from being linked in (-ffunction-sections -fdata-sections and --gc-sections) but one function per file is probably most reliable.


    • I'm ignoring C++ name mangling here for the sake of simplicity

提交回复
热议问题