Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read File At Compile Time (constexpr or other)

Does C++17 offer any way to load/read a file at compile time? More specifically, I want to load a file's content into a const char* or std::string_view, etc. For example:

    constexpr const char* read_file_content(const char* file_path) {
        /* should read in the content of the file and return it */
        return "";
    }

    constexpr const char* file_path    = "some/folder/file.json";
    constexpr const char* file_content = read_file_content(file_path);


I've come across this answer Is it possible to read a file at compile time? from 2014. The solution by teivaz works perfectly, using some macro & #include magic. However, it requires the input file to be changed: the file should enclose its content in STR( ... ), which may not always be possible.

Since the above answer is quite old, I thought maybe things have changed, and perhaps C++17 (or possibly C++20) offers some functionality to overcome this issue.

like image 753
Phil-ZXX Avatar asked Dec 31 '22 21:12

Phil-ZXX


1 Answers

C++20 might ship with std::embed. Have a look at P1040. If this lands, you can

constexpr std::span<const std::byte> someBytes = std::embed("pathToFile");
like image 148
lubgr Avatar answered Jan 09 '23 11:01

lubgr