How to Compile a Bootloader for an Arduino Mega 2560

Why might this be needed?

This can be useful if you want to add or modify the functionality of an existing bootloader or fix an error within it.

Let’s fix the EEPROM reading error in the standard Arduino Mega 2560 bootloader.

As an example, let’s describe how to fix an error in the bootloader for the Arduino Mega 2560, which prevents the correct reading of EEPROM memory through USB using the standard bootloader that has been supplied with all Arduino Mega 2560 boards for the past 8 years (as of 2023).

Download the bootloader’s source code.

1) It is recommended to download the source code of the most up-to-date official version of the bootloader for Arduino Mega 2560 from the official repository:
The file with the bootloader we are interested in is located at this path: ArduinoCore-avr-master\bootloaders\stk500v2, and it is named stk500boot.c
Let’s make the necessary corrections
In our case, fixing the error is relatively easy. You need to add the following lines of code after line 1066 with the text: /* Read EEPROM */
Add a new line with the text: uint16_t ii = address >> 1;
Replace lines 1068 to 1070 with:
    EEARL = ii; // Setup EEPROM address
    EEARH = ((ii >> 8));
    address += 2; // Select next EEPROM byte
It should look like this:
/* Read EEPROM */
uint16_t ii = address >> 1;
do {
         EEARL=ii;// Setup EEPROM address
         EEARH=((ii >> 8));
         address += 2; // Select next EEPROM byte
         EECR|=(1<<EERE);// Read EEPROM

Let’s compile the modified bootloader for an Arduino Mega 2560

Now, you need to compile this C program into a file prepared for uploading to the FLASH memory of the Arduino Mega 2560. However, some preparation is required for this:
2) Download and install the WinAVR package, make sure to leave the Add Directories tp PATH checkbox selected during installation.
3) Download the archive with fixes for this package from here: 
msys-1.0-vista64 (fixed) (42 downloads)
4) Replace the msys-1.0.dll file, which is located at this path: C:\WinAVR-20100110\utils\bin with the file from the archive containing fixes. If you don’t do this, you will encounter an error during the compilation process: “fatal error: opening dependency file .dep/stk500boot.o.d: No such file or directory”
5) Open a console or terminal window and navigate to the folder containing the bootloader source code. If the repository from step #1 was downloaded to the root of the C drive, you can navigate to the folder using the following command:
cd C:\ArduinoCore-avr-master\bootloaders\stk500v2
6) Execute the “make mega2560” command.
If everything went well, the console output should look like this:
Now the bootloader is ready to be loaded into the Arduino. You can read about how to do it in this article:
And the corrected and compiled bootloader can be downloaded from here: 
Fixed bootloader for Arduino Mega 2560 (62 downloads)