Reputation:
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?
Upvotes: 0
Views: 1263
Reputation: 882336
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.
Upvotes: 0
Reputation: 792867
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'.
Upvotes: 1
Reputation: 301055
Take a look at "#include" a text file in a C program as a char[] for a possible alternative which might address your needs.
Upvotes: 2
Reputation: 4141
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.
Upvotes: -1