2

Let's say I'm including a header file that has tons of functions.

#include "1000Functions.h"

Function1(42);
Function2("Hello");
Function1000("geeks!");

But, I just want to use a few of the functions from the header. After preprocessing, compiling, and linking (for example, with g++), would my program include all 1000 functions, or just the 3 that I used?

Rob
  • 105
  • 1
  • 1
  • 9
  • 3
    related/dupe: https://stackoverflow.com/questions/6215782/do-unused-functions-get-optimized-out#:~:text=No%3A%20for%20unused%20globally%20available,if%20there%20exist%20internal%20references. – NathanOliver Jul 03 '20 at 00:44
  • *Let's say I'm including a header file that has tons of functions.* -- What is in the `h` files are probably not function bodies, only function prototypes. – PaulMcKenzie Jul 03 '20 at 00:45
  • in general, you "pay for what you use". Only the object code for the functions you use should end up in your final executable code. – ttemple Jul 03 '20 at 01:29
  • 1
    Depends on the compiler and the compiler optimization level. Some compilers may be lazy at the lowest optimization level and throw everything in (this is the faster build). At higher optimization levels, the compiler would eliminate any unused functions (and the linker would help too). You can verify this by having the compiler generate a "map" file or a cross-reference of all the functions. – Thomas Matthews Jul 03 '20 at 01:56
  • Please read a good [C++ programming book](https://stroustrup.com/programming.html) then the documentation of [GCC](http://gcc.gnu.org/) and of [GDB](https://www.gnu.org/software/gdb/). See also [this C++ reference](https://en.cppreference.com/w/cpp) – Basile Starynkevitch Jul 03 '20 at 03:32

1 Answers1

0

I found this article that was useful. Using objdump -tC ProgramName can show you the unnecessary code that ends up being loaded into .text when your program is loaded into the memory.

Link-time optimization was what I was looking for, which worked for me once I added both of these tags to the linking command, not just -flto.

-O2 -flto
Rob
  • 105
  • 1
  • 1
  • 9