Is there a function or a method to load data from a file into a variable during compile time in C++?
Asked
Active
Viewed 384 times
0
-
Why would you do that? – sebastian Aug 23 '20 at 17:16
-
How about define the string in the header file? – cmj Aug 23 '20 at 17:16
-
2You can `#include` any file you want. – Buddy Aug 23 '20 at 17:17
-
I would rather load the data from the file, I.E, fstream style, but how would you do that statically? – KapowCabbage Aug 23 '20 at 17:20
-
3You might want to look at [this post](https://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char). – G.M. Aug 23 '20 at 17:46
-
If the marked original does not answer your question, edit this question to specify more clearly what you need to do and to distinguish that from the other question. – Eric Postpischil Aug 23 '20 at 21:39
2 Answers
1
Is there a function or a method to load data from a file into a variable during compile time in C++?
Only constexpr functions can be evaluated at compile time. As far as I'm aware, no file processing function is constexpr, hence the answer to your question is "no".
You may consider other options:
- have that file contain a properly formatted and quoted string and put
#includedirective where an initializer for your string should have been (on a separate line, obviously); - resort to good-old makefile magic to run a script which would convert the text file to a proper C++ source when compiling the project.
Igor G
- 1,838
- 6
- 18
-
"as far as I'm aware, no file processing function is constexpr" Yes that is correct and that is intentional. A `constexpr` function must not have any source of UB because otherwise you could not guarantee the compilation correctness. So you can't have any kind of constexpr IO operation. – bolov Aug 23 '20 at 21:06
-2
You can do it during configuration time with cmake
https://cmake.org/cmake/help/latest/command/configure_file.html
Krzysztof Mochocki
- 188
- 2
- 10