Home >Backend Development >C++ >How Can I Embed Resources into My GCC Executable?
Embedding Resources in Executables with GCC
When developing C/C applications with GCC, it can be convenient to embed external binary data directly into the executable. This simplifies distribution by eliminating the need for separate resource files.
GCC's Embedding Capabilities
GCC offers two main approaches for resource embedding:
Using ld:
Using bin2c/bin2h Utilities:
Example with ld
Here's a more detailed example using ld:
#include <stdio.h> extern char _binary_foo_bar_start[]; extern char _binary_foo_bar_end[]; int main(void) { printf("Address of start: %p\n", &_binary_foo_bar_start); printf("Address of end: %p\n", &_binary_foo_bar_end); for (char* p = _binary_foo_bar_start; p != _binary_foo_bar_end; ++p) { putchar(*p); } return 0; }
In this example, a file named foo.bar is converted into an object file (foo.bar.o) using:
ld -r -b binary -o foo.bar.o foo.bar
The linker then includes foo.bar.o when building the executable, allowing access to the binary data through the symbols _binary_foo_bar_start and _binary_foo_bar_end.
Size Determination
To determine the size of the embedded resource, use:
unsigned int iSize = (unsigned int)(&_binary_foo_bar_end - &_binary_foo_bar_start);
The above is the detailed content of How Can I Embed Resources into My GCC Executable?. For more information, please follow other related articles on the PHP Chinese website!