0

Is there a function or a method to load data from a file into a variable during compile time in C++?

KapowCabbage
  • 65
  • 1
  • 8

2 Answers2

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 #include directive 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