Home > Backend Development > C++ > How Can I Embed Resources into My Executable Using GCC?

How Can I Embed Resources into My Executable Using GCC?

Susan Sarandon
Release: 2024-12-14 15:07:11
Original
753 people have browsed it

How Can I Embed Resources into My Executable Using GCC?

Embedding Resources in Executable Using GCC: A Detailed Guide

Embedded C/C applications often require the inclusion of external binary data, such as shader code, fonts, or images. This can present challenges when distributing the application as a single executable. GCC provides solutions to simplify this process.

Option 1: Using ld's Object File Generation

One method is to leverage ld's capability to convert any file into an object file. This allows you to incorporate the binary data into your application as an object during the linking stage. To do this, use the following command:

ld -r -b binary -o binary.o foo.bar  # then link in binary.o
Copy after login

Option 2: Utilizing bin2c/bin2h Utilities

Another option is to use a bin2c/bin2h utility to convert the external file into an array of bytes. This array can then be included in your code as a constant, allowing you to access the binary data as needed.

Example: Embedding Data Using ld -r -b Binary

Consider the following example, where we have a file named foo.bar containing some text:

foo.bar: This is an example text.
Copy after login

To embed this text within our C program, we can use the following code:

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

Getting the Resource Size

To obtain the size of the embedded resource, you can use the following code:

unsigned int iSize =  (unsigned int)(&_binary_foo_bar_end - &_binary_foo_bar_start)
Copy after login

Conclusion

GCC provides multiple methods for embedding external binary data into C/C executables. These techniques simplify the distribution of compact, self-contained applications that incorporate resource files within the executable itself.

The above is the detailed content of How Can I Embed Resources into My Executable 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