Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate an array at compile-time from file

Tags:

c++

arrays

I am cross compiling a program for a bare-metal environment and I want to have an array populated with the data I have stored in a file. Is there a way to do this read during compile-time?

Reason: Copy-pasting the data into the source seems ugly.

like image 590
Moberg Avatar asked Jan 10 '14 11:01

Moberg


1 Answers

Part of your build process can be to run a program which takes the file as input and generates a C++ source file which defines it as an array, something like:

char arrayFromFile[] = {
    0x01, 0x02, 0x99, ...  and so on
};

The program itself could be part of your source code.

Then just compile that program later in the build cycle. For example, you may have the following makefile segment:

generate: generate.cpp
    g++ -o generate generate.cpp    # build data generator

data.cpp: data.dat
    generate data.dat >data.cpp     # create c file with data

prog: prog.cpp data.cpp
    g++ -o prog prog.cpp data.cpp   # create program from source and data
like image 144
paxdiablo Avatar answered Sep 28 '22 08:09

paxdiablo