Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does code in header file increases binary size?

Consider this:

class Foo{
      void func1(){
            /*func1 code*/

      }

      void func2(){
            /*func2 code*/

      }


};

Case 1: class Foo in Foo.h

Case 2: class Foo nicely seperated among Foo.h and Foo.cpp

Various other cpp files include Foo.h

My question is...Will Case 1 lead to a bigger binary?

like image 969
Aman Aggarwal Avatar asked Oct 16 '09 05:10

Aman Aggarwal


2 Answers

Maybe it will, maybe it won't. It really has nothing to do with header files. What matters here is that your member functions are defined in the class definition. When member functions are defined like that, they are treated as inline functions. If the compiler decides not to actually inline any calls to these functions, there won't be any impact on code size. If the compiler decides to inline any (or all) of the calls, the answer would be "it depends". Inlining calls to small functions might result in increased code size as well as in decreased code size. This all depends on the function itself and on the compiler's capabilities (optimization capabilities specifically).

like image 167
AnT Avatar answered Sep 20 '22 07:09

AnT


If compiler decides not to inline those functions, and generate separate body for them, these bodies will appear in each object file who uses them, but with special flag for linker - 'weak symbol'. When linker finds this flag, it will combine all symbols with that name into only one resulting symbol (maybe it will produce error message if bodies or sizes of such symbols are different)

Also RTTI info and vtables also use same scenario.

With dynamic libraries, weak symbol joining may happen at run-time, if they uses the same class.

like image 38
Xeor Avatar answered Sep 23 '22 07:09

Xeor