4

I have an embedded C project I am compiling using eclipse. I need to read a binary file into the application code as an array of constants.

This binary file is ~200kB and needs to be part of the application code so that the application code can read the binary image at anytime and load it into another device on the board that needs this initialization image.

I would normally load the image into a non-volatile memory on the board, then read it and move it, but that is not feasible here, it has to be part of the executable image.

I can do this in the makefile by linking the .bin file to a certain address, or in the C code something like

const char binFileImage [] = { file.bin };

This obviously does not work, but I have not come up with syntax that would work.

FYI, the file.bin really is a binary file.

Any thoughts on how to do this?

user694733
  • 15,208
  • 2
  • 42
  • 68
Martin
  • 107
  • 1
  • 6
  • Possible duplicate of [Is there a way to load a binary file as a const variable in C at compile time](http://stackoverflow.com/questions/22455274/is-there-a-way-to-load-a-binary-file-as-a-const-variable-in-c-at-compile-time) – Andrew Henle Nov 03 '15 at 17:35

1 Answers1

5

Using a linker script to put the binary file in a specific address is probably the best and simplest solution.

Other solutions include using some program that is called by the makefile to convert the file into a source file containing a valid array definition. For example, lets say the file starts with the values 0x23, 0x05, 0xb3 and 0x8f, then the automatically generated source file could look something like

const uint8_t binary_file_data[] = {
    0x23, 0x05, 0xb3, 0x8f, ...
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Hi, I see where you are going with this, but if I look a the tile I see – Martin Nov 03 '15 at 15:28
  • ff ff ff eb ff ... not 0xff 0xff -- I would need an application to do the conversion, I am not aware of a program that would work well for that and I was hoping to do it on the fly as the .bin file may change – Martin Nov 03 '15 at 15:30
  • 2
    @user2969503 Write your own. Apart from that, you could also use `objcopy` from the binutils to do this. – fuz Nov 03 '15 at 15:33
  • 2
    On Linux: `ld -r -b binary -o binary.o binary.file`. See http://stackoverflow.com/questions/22455274/is-there-a-way-to-load-a-binary-file-as-a-const-variable-in-c-at-compile-time – Andrew Henle Nov 03 '15 at 17:36