所以我想要一个可以有条件地包含为代码或字符串的文件。 像这样:
#define something
#include "myfile.inc"
#undef something
const char myfileasastring =
#include "myfile.inc"
myfile.inc 将是这样的简单代码:
something // anything extra here is fine as long as it goes away in the code include case
int myfunc() { return 23; }
这可能吗?我尝试使用 #define something R("mystring 并用它启动 myfile 但这似乎不起作用。
我的具体用例是一个 GLSL 着色器,在 GL 下运行时,我需要将其作为字符串传递给 GL 驱动程序,但在软件仿真中运行时,我想将其编译为 CPP 代码。
我希望两种情况都使用相同的文件。我知道项目/制作/构建级别的许多解决方法,即使只是剪切和粘贴也不是很糟糕,但是如果有一个可移植的编译器级别的方法来执行此操作会很好。
未检测到欺骗。我知道如何包含一个 xor 另一个,但不包含其中一个或包含同一文件。我也知道如何使用外部工具来做到这一点,我真的只是想知道是否只是在普通的、可移植的 c++11 中想知道。这可能是不可能的。 (尝试再次删除 dupe 标签。如果您仍然认为它是一个 dupe,请发表评论)
最佳答案
创建一个名为 include.cpp
的文件,其中包含以下内容:
int f()
{
return 42;
}
然后,main.cpp
(灵感来自 https://stackoverflow.com/a/25021520/4323 ):
#include <iostream>
#include "include.cpp"
int main()
{
const char* const str =
R"(include(include.cpp))"
;
std::cout << str << '\n';
return f();
}
include()
语法是什么?那是m4!所以你这样编译:
m4 main.cpp | g++ -x c++ -std=c++11 -
或者如果您不能在编译命令中使用管道:
g++ -x c++ -std=c++11 <(m4 main.cpp)
如果您使用第二个选项,您将需要一个-I
规则来告诉编译器在哪里#include "include.cpp"
因为源文件"exists"in /dev
(这是一种 Bash 主义)。您可以在顶部使用 include(include.cpp)
而不是使用 #include
,这两种方法都可以。
程序打印 include.cpp
中的代码,然后调用其中的函数。
对于使用 m4,我深表歉意,但它在很多系统上都可用(您可以为其他人编写自己的简单实现)。
关于c++ - 如何将文件同时作为字符串和代码包含在 cpp 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103029/