Reducing code size on Arduino Ethernet boards

The Ethernet library grew in size several KB from 0022 to 1.0, which is a big deal when you only have 32 KB to play with. You can save about 2 KB by compiling out DNS support:

Wrap the following pieces of code in #if WITH_DNS

  • Dns.cpp and Dns.h:
    The entire file
  • EthernetClient.h and EthernetClient.cpp:
    int connect(const char* host, uint16_t port)
  • EthernetUDP.h and EthernetUDP.cpp:
    int beginPacket(const char *host, uint16_t port)
  • Client.h:
    virtual int connect(const char *host, uint16_t port)
  • Udp.h:
    virtual int beginPacket(const char *host, uint16_t port)

Add #include "EthernetUDP.h" to EthernetUDP.cpp, since it’s currently relying on the indirect include from Dns.h.

5 thoughts on “Reducing code size on Arduino Ethernet boards”

  1. This has helpfull. It reduced about 3Ks on my compile. Any idea if killing DHCP would reduce the compilation output. I was hoping to maintain DNS to be able to connect to a dymanic ip – based website, but use a static address on the arduino since it’s less problematic. 

    With the ethernet library and my library, I was 100 bytes over the limit. Without DNS I have 3K free.

    1. You can save a lot if you are currently using it (e.g., using the one argument Ethernet.begin), but very little if you aren’t already using it, as the linker is doing a good job of stripping the dead code.

      As a quick test, I wrapped the one-arg begin and all of DHCP.cpp / DHCP.h with a define in an existing project:
      – Using two arg begin (no DHCP but no mods): 15916 bytes
      – Using two arg begin, with DHCP compiled out: 15892 bytes
      – Using one arg begin (using DHCP lib): 18088 bytes

  2. Tried your fix but I now get an error:
    cannot declare variable ‘client’ to be of abstract type ‘EthernetClient’

    Any idea what might be wrong?

    Also I couldn’t find the Client.h and Udp.h files, so never made the fix in those.

    1. Client.h and Udp.h are in the main Arduino source folder.
      On Ubuntu it is ‘ /usr/share/arduino/hardware/cores/arduino ‘

  3. Thanks for your tutorial, I followed your instruction but the size didn’t change a bit I dont know why? can you please upload the library

Leave a Reply

Your email address will not be published. Required fields are marked *