Home >Backend Development >C++ >How Can I Seamlessly Embed Resources into Executables Using GCC?
To effortlessly embed external binary data within C/C applications compiled by GCC, consider the following methods:
Utilizing ld's Object Creation Feature:
ld, the linker, offers the capability to convert any file into an object. To embed a file, run the command:
ld -r -b binary -o binary.o foo.bar # then link in binary.o
This creates an object file ("binary.o") with symbols such as:
For instance, to access the contents of a simple text file embedded using this method:
#include <stdio.h> extern char _binary_foo_bar_start[]; extern char _binary_foo_bar_end[]; int main(void) { // Print the contents of the embedded resource for (char* p = _binary_foo_bar_start; p != _binary_foo_bar_end; ++p) { putchar( *p); } return 0; }
Employing a Bin2c/Bin2h Utility:
These utilities convert files into an array of bytes. Integrate the resulting array into your code.
Example with ld Object Creation:
Here's how to incorporate a resource into an object file:
ld -r -b binary -o foo.bar.o foo.bar
The resulting object file contains these symbols:
To access the embedded resource within your code:
unsigned int iSize = (unsigned int)(&_binary_foo_bar_end - &_binary_foo_bar_start);
This provides an alternative method to determine the resource size.
The above is the detailed content of How Can I Seamlessly Embed Resources into Executables Using GCC?. For more information, please follow other related articles on the PHP Chinese website!