Last active
May 12, 2025 04:08
-
-
Save mmozeiko/ed9655cf50341553d282 to your computer and use it in GitHub Desktop.
Include binary file with gcc/clang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define STR2(x) #x | |
#define STR(x) STR2(x) | |
#ifdef _WIN32 | |
#define INCBIN_SECTION ".rdata, \"dr\"" | |
#else | |
#define INCBIN_SECTION ".rodata" | |
#endif | |
// this aligns start address to 16 and terminates byte array with explict 0 | |
// which is not really needed, feel free to change it to whatever you want/need | |
#define INCBIN(name, file) \ | |
__asm__(".section " INCBIN_SECTION "\n" \ | |
".global incbin_" STR(name) "_start\n" \ | |
".balign 16\n" \ | |
"incbin_" STR(name) "_start:\n" \ | |
".incbin \"" file "\"\n" \ | |
\ | |
".global incbin_" STR(name) "_end\n" \ | |
".balign 1\n" \ | |
"incbin_" STR(name) "_end:\n" \ | |
".byte 0\n" \ | |
); \ | |
extern __attribute__((aligned(16))) const char incbin_ ## name ## _start[]; \ | |
extern const char incbin_ ## name ## _end[] | |
INCBIN(foobar, "binary.bin"); | |
int main() | |
{ | |
printf("start = %p\n", &incbin_foobar_start); | |
printf("end = %p\n", &incbin_foobar_end); | |
printf("size = %zu\n", (char*)&incbin_foobar_end - (char*)&incbin_foobar_start); | |
printf("first byte = 0x%02hhx\n", incbin_foobar_start[0]); | |
} |
ohh those are some good tips. I'll try them out
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You don't need to switch to C23. Clang supports #embed as extension even in C99 or whatever standard. It'll just be extra warning, but that you can silence it with pragma or just globally.
If you want to figure out how to make .incbin work, then you can enable assembly output with
-S
for someconst uint8_t data[] = { ... }
array and then look how variable declaration looks in assembly, then replicate the same thing in inline asm. Or just simply look in godoblt - there you need turn off "Directives" under "Filter".