Home >Backend Development >C++ >How to Embed Resources (e.g., Shader Code) into GCC Executables?

How to Embed Resources (e.g., Shader Code) into GCC Executables?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 11:52:10851browse

How to Embed Resources (e.g., Shader Code) into GCC Executables?

Embedding Resources in Executable Using GCC

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:

  • Using ld's Capability to Convert Files to Objects:
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.

  • Using bin2c/bin2h Utilities:

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)(&amp;_binary_foo_bar_end - &amp;_binary_foo_bar_start);

    printf("Resource size: %u\n", iSize);
    printf("Address of start: %p\n", &amp;_binary_foo_bar_start);
    printf("Address of end: %p\n\n", &amp;_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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn