Anand
Anand

Reputation: 1122

C++ program to dump a boiler plate C++

I have a C++ program which dumps out a C++ program. Some of the functions are boiler plate code and certain functions has boiler plate code and code tailored based on a few variables.

A simplified example is presented below:

// 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;
}

The output.cc gets compiled and user gets the *.so file. The user does not have access to output.cc.

I wanted to rewrite this since it is difficult to read the boiler plate code when it is inside fout and having escaped quotes makes it a nightmare. Hence I thought of storing the functions in a separate file. For example have bp() in bp.cc:

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

Then the main file can be written as

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

    dst << src.rdbuf();
}

In case of mix() I would use the Form-Letter Programming by storing the function mix() in mix.cc.

When the functions bp() and mix() were dumped using fout as in Snippet:1, all I had to do was ship the executable since the Snippet:1 is self-contained. But

Upvotes: 1

Views: 1575

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

You can use raw string literals and just put the code into one of those:

#include <iostream>

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

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

Upvotes: 3

Related Questions