Hacker News new | ask | show | jobs
by gucci-on-fleek 90 days ago
My preferred technique (where #embed isn't available) is to use objcopy:

  $ echo 'Hello, world!' > hello-world.txt 
  $ objcopy --input-target=binary --output-target=elf64-x86-64 \
      hello-world.txt hello-world.o
  $ cat <<EOF > embed.c
      #include <stdint.h>
      #include <stdio.h>
  
      #define EMBED(NAME)                                \
          extern const uint8_t _binary_##NAME##_start[]; \
          extern const uint8_t _binary_##NAME##_size[];
      #define DATA(NAME) _binary_##NAME##_start
      #define SIZE(NAME) (size_t)_binary_##NAME##_size
  
      int main() {
          EMBED(hello_world_txt);
  
          printf("%.*s", (int)SIZE(hello_world_txt), DATA(hello_world_txt));
      }
  EOF
  $ gcc hello-world.o embed.c -o hello-world
  $ ./hello-world
  Hello, world!