Embed Data Resources in Executables with GCC
Embedding binary data within an executable can be immensely beneficial for distributing portable applications. As an example, embedding shader code as binary data instead of storing it as source code can greatly enhance practicality.
To accomplish this, GCC offers two primary options:
Using ld to Embed Binary Files
The linker, ld, allows the conversion of any file into an object file:
ld -r -b binary -o binary.o foo.bar # Subsequently link in binary.o
This approach creates symbols such as _binary_foo_bar_start, _binary_foo_bar_end, and _binary_foo_bar_size within the object file.
Leveraging bin2c/bin2h Utilities
Alternatively, you can employ bin2c/bin2h utilities to transform any file into an array of bytes.
Example of Data Embedding Using ld
Below is an illustrative example of how to embed data using ld:
#include <stdio.h> extern char _binary_foo_bar_start[]; // Address of the embedded resource extern char _binary_foo_bar_end[]; int main(void) { int iSize = (unsigned int)(&_binary_foo_bar_end - &_binary_foo_bar_start); printf("Size of embedded resource: %d\n", iSize); for (char* p = _binary_foo_bar_start; p != _binary_foo_bar_end; ++p) putchar(*p); return 0; }
The above is the detailed content of How Can I Embed Binary Data Resources into Executables Using GCC?. For more information, please follow other related articles on the PHP Chinese website!