Home > Backend Development > C++ > How Can I Embed Binary Data Resources into Executables Using GCC?

How Can I Embed Binary Data Resources into Executables Using GCC?

Patricia Arquette
Release: 2024-12-18 21:35:17
Original
451 people have browsed it

How Can I Embed Binary Data Resources into Executables Using GCC?

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
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template