F
F
floppa3222021-11-29 22:16:49
C++ / C#
floppa322, 2021-11-29 22:16:49

header-only. Does the size of the binary suffer?

Do I understand correctly that if there is an implementation of methods in header files, only compilation time will suffer, and this will not affect the size of the binary in any way?

Well, in frequency, then the question will be appropriate: is the size of the binary inflated due to the large number of templates? Since they need to be implemented in headers

According to the first comment to a similar question , it seems to be so, but I would like clarifications :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2021-11-29
@Lite_stream

For C++ templates, a special exception had to be added to the linkers, because the templated functions would be repeated in every available object file.
For the sake of testing, I made such a project

// MAIN.CPP
#include <iostream>

#include "tmpl.h"

void doFile1();

int main()
{
    const char* x = "main";
    outThing(x);
    doFile1();
    return 0;
}

// FILE1.CPP
#include "tmpl.h"

void doFile1()
{
    const char* x = "doFile1";
    outThing(x);
}


// TMPL.H
#pragma once

#include <iostream>

template <class T>
void outThing(const T& x)
{
    std::cout << "The thing is " << x << std::endl;
}

What is x for? OutThing(char[5]&) and, accordingly, char[8]& appeared when unscrambled.
And now the linker dump
Discarded input sections

 .text$_Z8outThingIPKcEvRKT_
                0x0000000000000000       0x50 debug/main.o

Linker script and memory map

.text$_Z8outThingIPKcEvRKT_
                0x0000000140002900       0x50 debug/file1.o
                0x0000000140002900                void outThing<char const*>(char const* const&)

Ну и ещё парочка структур для раскрутки стека и подстановки адресов…

So even with -O0 it won't duplicate anything. Yes, and the logic is clear: what to duplicate, what not to duplicate - one horseradish will require special logic, and there is little difference.

V
Vasily Melnikov, 2021-12-01
@BacCM

The first question is no.
For the second part. The size of the binary "suffers" only from how many options for instantiating the template will be in the code.
roughly speaking:

template <class T> 
T foo (T t)
{
  return t;
}
/// вызовы гдет-то.

foo(10); /// увеличивает размер бинарника генерится код int foo(int)
foo(10.0); /// увеличивает размер бинарника генерится код double foo(double)
foo(1); /// не увеличивает размер бинарника генерится используется код int foo(int)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question