views:

637

answers:

4

Hi,

I have the following problem. I want to include a multi-line textfile as #define, i.e. what I need is a constant that stores the value of the text file. Example:

File 'f.txt': This\nis\n\nsome\ntext

and I want to initialize a constant (at compile time) in the style of

#define txtfile "This\nis\na\ntextfile"

where the string "This\nis\na\ntextfile" is obtained from concatenating the lines in file f.txt. Is there any way to achieve this using preprocessor commands/macros?

Thanks in advance

A: 

One might come up with an idea like the following:

f.txt:

This \
is \
some \
text \

code.c:

#define txtfile "\
#include "f.txt"
"

But I don't think this would work. The include line would just be regarded as a String.

Adrian Lang
+2  A: 

Take a look at http://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char for a possible alternative which might address your needs.

Paul Dixon
+1  A: 

This isn't directly possible, as the textfile needs processing first. You could write a fairly simple script that performed the appropriate escaping and added the #define creating a suitable header file.

Typically you don't actually need the text file as a preprocessor macro expansion, though, you need the file data to appear in the object file and to be accessible as though it where an extern char[].

To do this there are two approaches. The lightweight way is to use an assembler like yasm with an incbin directive to produce an object file which has the file data as a labelled section. e.g.:

    global f_txt
f_txt:
    incbin "f.txt"

Then in the C file you can declare:

extern char f_txt[];

The more portable way is to use a utility like xxd -i to convert the data into an C file with the char array written out 'long hand'.

Charles Bailey
objcopy also works for generating an object file: http://www.linuxjournal.com/content/embedding-file-executable-aka-hello-world-version-5967
Jeff M
A: 

What you're probably going to have to do is have a separate pre-processor program that takes your input file (f.txt) and a code section in your special source file (program.cppx) like:

#superdefine txtfile f.txt

The pre-pre-processor you'll have to write yourself but it'll basically replace the #superdefine lines with the equivalent #define lines based on the file content, producing a file program.cpp which you can then feed into the real compiler.

This is quite easy to achieve under UNIXes if you're using a make variant. May not be so easy using an IDE.

paxdiablo