Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49329

Reducing C++ code size

I am working on a dynamic language (that compiles into C++) for microcontrollers, being a CS guy I decided to do it properly first then worry about optimization. Below is how my object system is structured,



Base (Interface)
|
|---- Number (Interface)
|      |
|      |-- Int
|      |-- Float
|
|---- Char
|
|---- Sequence (Interface)
|      |
|      |-- LinkedList
|
|---- Function (Interface)
      |
      |-- Built-in Functions (Functors)

Now that everything is working generated code size started to be a problem, every operation has to be represented by a functor, (+,- while,for etc..) so I am guessing that is causing the bump in code size or I pass everything as base class then cast as needed so I have a lot of casts, currently a simple led on/off loop is costing 15 kbytes even though it doesn't use all object types (6 functors + 4 integers).

I have tried various avr-gcc options that did not reduce code size. So I am wondering how can I figure out which part of the code is consuming so much space?

Upvotes: 3

Views: 6441

Answers (2)

David Grayson
David Grayson

Reputation: 87406

During the link step, you should have avr-gcc generate a map file so you can look at it and see what is taking up so much space.

Be sure to use the -ffunction-sections compilation option and the -Wl,-gc-sections linker option to remove unused functions from the binary.

What features of C++ are you using? Some of them (like classes and namespaces) are cheap, while others are very expensive (such as exception handling). Interfaces and virtual functions will be more expensive than just having classes and subclasses.

I saw a good talk once called "The Inefficiency of C++: Fact or Fiction?" produced by IAR. It went through each advanced feature of C++ and assigned a cost to it. It was mainly geared towards people developing for the ARM architecture but it could still be valuable to you. Here are the slides: https://www.iar.com/globalassets/about-us/events/atc2015/inefficiencies-of-c.pdf

Upvotes: 9

sergio
sergio

Reputation: 69027

Trivial remark, apart from supporting David's suggestions: make sure you are not compiling in debug mode and that you strip off all the symbols from your executable to reduce its size to a minimum.

Upvotes: 2

Related Questions