Is it possible to read a file at compile time?

前端 未结 3 1354
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 13:21

I am wondering if it is possible in C++11/14 to actually read files at compile time. For example the following code will only compile if it can successfully read the file.

相关标签:
3条回答
  • 2020-12-03 13:48
    #define STR(x) #x
    
    const char* a =
    { 
    #include "foo.glsl" 
    };
    

    and foo.glsl should enclose its content in STR( ... )

    upd. This will properly handle commas

    #define STRINGIFY(...) #__VA_ARGS__
    #define STR(...) STRINGIFY(__VA_ARGS__)
    
    0 讨论(0)
  • 2020-12-03 14:07

    I have done something like this. See if this will give you what you want.

    Add a command line option to the program that checks for the existence and validity of the input file.
    That option should exit the program with an error code if the file does not exist, or is not valid.

    In your make file, add a call to the program (using that command line option), as the final build step.

    Now when you build the program, you will get an error if the proper files are not available or not valid.

    0 讨论(0)
  • 2020-12-03 14:08

    Building on teivaz's idea, I wonder if the usual "stringize after expansion" trick will work:

    #define STRINGIZE(...) #__VA_ARGS__
    #define EXPAND_AND_STRINGIZE(...) STRINGIZE(__VA_ARGS__)
    
    constexpr std::string shader_source = EXPAND_AND_STRINGIZE(
    #include "~/.foo.glsl"
    );
    


    Still, I would go for a conventional extern const char[] declaration resolved to the content by the linker. The article "Embedding a File in an Executable, aka Hello World, Version 5967" has an example:

    # objcopy --input binary \
              --output elf32-i386 \
              --binary-architecture i386 data.txt data.o
    

    Naturally you should change the --output and --binary-architecture commands to match your platform. The filename from the object file ends up in the symbol name, so you can use it like so:

    #include <stdio.h>
    
    /* here "data" comes from the filename data.o */
    extern "C" char _binary_data_txt_start;
    extern "C" char _binary_data_txt_end;
    
    main()
    {
        char*  p = &_binary_data_txt_start;
    
        while ( p != &_binary_data_txt_end ) putchar(*p++);
    }
    
    0 讨论(0)
提交回复
热议问题