Home >Backend Development >C++ >How to Embed Resources (e.g., Shader Code) into GCC Executables?
Problem:
Embedding external binary data within a C/C application compiled by GCC, specifically shader code for more efficient distribution as a single executable file.
Solutions:
GCC provides two solutions:
ld -r -b binary -o binary.o foo.bar # Then link in binary.o
This command converts the file foo.bar into an object file (binary.o) that can be linked into the program.
These utilities convert any file into an array of bytes, which can then be included in the program.
Updated Example:
#include <stdio.h> extern char _binary_foo_bar_start[]; extern char _binary_foo_bar_end[]; int main(void) { // Get the resource size (workaround) unsigned int iSize = (unsigned int)(&_binary_foo_bar_end - &_binary_foo_bar_start); printf("Resource size: %u\n", iSize); printf("Address of start: %p\n", &_binary_foo_bar_start); printf("Address of end: %p\n\n", &_binary_foo_bar_end); // Dump resource contents for (char* p = _binary_foo_bar_start; p != _binary_foo_bar_end; ++p) { putchar( *p); } return 0; }
This example uses the ld-based solution to embed the file foo.bar into the executable. It then retrieves the resource size using a workaround, and dumps the resource contents to the console.
The above is the detailed content of How to Embed Resources (e.g., Shader Code) into GCC Executables?. For more information, please follow other related articles on the PHP Chinese website!