【问题标题】:C++ program to dump a boiler plate C++用于转储样板的 C++ 程序 C++
【发布时间】:2014-03-28 09:19:35
【问题描述】:

我有一个 C++ 程序,它转储出一个 C++ 程序。一些函数是样板代码,某些函数有样板代码和基于一些变量定制的代码。

下面是一个简化的例子:

// Snippet: 1
#include <fstream>

using namespace std;
int main()
{
    ofstream fout("output.cc");

    // bp() has just boiler plate code
    fout << "void bp() {" << endl;
    fout << "std::cout << \"Hello World!\" << std::endl" << endl;
    // a few hundred lines of C++ code send to fout
    fout << "}" << endl;

    // mix() has boiler plate + some custom code
    int size = 4096;
    fout << "void mix() {" << endl;
    fout << "char buffer[" << size << "];" << endl;
    // a few hundred lines of C++ code send to fout
    fout << "}" << endl;

    // compile output.cc into *.so and delete output.cc

    return 0;
}

output.cc 被编译并且用户得到*.so 文件。用户无权访问output.cc

我想重写它,因为当它在 fout 中时很难阅读样板代码,并且转义引号使它成为一场噩梦。因此我想到将函数存储在一个单独的文件中。例如在bp.cc 中有bp()

// file: bp.cc
void bp() {
    std::cout << "Hello World" << std::endl
    // a few hundred lines of C++ code 
}

那么主文件可以written

int main()
{
    std::ifstream  src("bp.cc");
    std::ofstream  dst("output.cc");

    dst << src.rdbuf();
}

如果是mix(),我将通过将函数mix() 存储在mix.cc 中来使用Form-Letter Programming

当函数bp()mix() 使用fout 转储(如Snippet:1)时,我所要做的就是发送可执行文件,因为Snippet:1 是自包含的。但是

  • 如果我将函数拆分为单独的文件 `bp()` 到 `bp.cc` 和 `mix()` 到 `mix.cc` 我如何将其作为单个可执行文件发送?我需要将 `bp.cc` 和 `mix.cc` 与可执行文件一起发送。我不希望用户访问 `bp.cc` 和 `mix.cc`。
  • 是否有比我建议的更好的方法来重写`Snippet:1` 以更好地满足我的需要?

【问题讨论】:

  • 您可能需要一个资源编译器之类的东西,将可执行文件捆绑到文件中。另一种选择可能是使用另一个小工具,它为给定的原始代码模板生成所有 'horrible' 转义语法,并为模板。
  • @πάνταῥεῖ 将此作为答案发布?
  • 哦,没关系 - 这是herehere
  • @anatolyg 感谢您提供链接。我真的不想回答这个问题,只有指针......
  • @anatolyg 嗯,这是双份吗?我认为latter 是这个问题最简洁的答案。

标签: c++


【解决方案1】:

您可以使用原始字符串文字并将代码放入其中之一:

#include <iostream>

char const source[] = R"end(
#include <iostream>
int main() {
    std::cout << "hello, world\n";
}
)end";

int main()
{
    std::cout << source;
}

【讨论】:

  • 我们还没有升级到 C++11。旧版本有解决方案吗?我们确实可以使用 Boost。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2010-09-06
  • 1970-01-01
相关资源
最近更新 更多