是否可以在编译时读取文件? [英] Is it possible to read a file at compile time?
问题描述
我想知道是否可能在C ++ 11/14在编译时实际读取文件。例如,下面的代码只有编译成功才能成功读取该文件。
constexpr std :: string shader_source = load 〜/ foo.glsl);你认为这是可能的吗?
p> 解决方案我知道我可以使用一些自定义工具在构建应用程序时执行此操作。 基于teivaz的想法,我想知道通常的stringize after expansion技巧是否可以工作:
#define STRINGIZE ...)#__VA_ARGS__
#define EXPAND_AND_STRINGIZE(...)STRINGIZE(__ VA_ARGS__)
constexpr std :: string shader_source = EXPAND_AND_STRINGIZE(
#include〜/ .foo .glsl
);
仍然,我会去一个常规的 extern const char []
声明由链接器解析到内容。文章将文件嵌入可执行文件(又称Hello World),版本5967 有一个例子:
#objcopy --input binary \
--output elf32- i386 \
--binary-architecture i386 data.txt data.o
应该更改 - output
和 - binary-architecture
命令以匹配您的平台。对象文件中的文件名以符号名称结尾,因此您可以这样使用:
#include< stdio .h>
/ *这里data来自文件名data.o * /
externCchar _binary_data_txt_start;
externCchar _binary_data_txt_end;
main()
{
char * p =& _binary_data_txt_start;
while(p!=& _binary_data_txt_end)putchar(* p ++);
}
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.
constexpr std::string shader_source = load("~/foo.glsl");
Do you think this could be possible?
I know that I could do this with some custom tool when building my application.
解决方案 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++);
}
这篇关于是否可以在编译时读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!