Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make the contents of an #include-file a compile-time constant in a cpp-file?

I have a file module.hpp

struct ModuleBase {
    virtual void run() = 0;
};

and a main.cpp program

int main() {
    cout << ...?...; // here should go the contents of module.hpp
}

What can I put at ...?... to let the contents of the header file printed here?

A basic idea would be

int main() {
    static const string content = R"(
#include <module.hpp>
)";
    cout << content;
}

but multi-line-strings are only available in C++11, and #include does not work inside multi-line strings (which is good)?

If there is a non-portable way for the gcc... that would be a start.

Clarification (update): The substitution should be done at compile time.

like image 710
towi Avatar asked Dec 20 '12 10:12

towi


People also ask

How do you make contents?

Click where you want to insert the table of contents—usually near the beginning of the document. On the toolbar ribbon, select References. Near the left end, select Insert Table of Contents. (Or select Table of Contents > Insert Table of Contents.

How do I manually create a table of contents?

To create a manual table, go to References > Table of Contents > Click the dropdown to reveal the option for Manual Table. Microsoft Word inserts a TOC with placeholders which you can now edit. You can modify this with your own fonts and colors. Do remember that you also have to insert the page numbers manually too.

How do you make a table of contents on paper?

To write a table of contents, you first write the title or chapter names of your research paper in chronological order. Secondly, you write the subheadings or subtitles, if you have them in your paper. After that, you write the page numbers for the corresponding headings and subheadings.


1 Answers

The only real solution I know is to write a small program which converts a file into a C++ definition of a string variable containing it. This is fairly simple to write: output a simple header along the lines of:

char const variableName[] =

Then copy each line of the file, wrapping it in "...\n", and escaping any characters necessary. (If you can be sure of C++11, then you might be able to do something with R"...", but I've no experience with this.)

[update: refering to the original question with a typo in it]: Your solution should not work; if it does, it is an error in the compiler. According to §2.2, tokenization occurs before the execution of preprocessing directives. So when the execution of preprocessing directives occurs, you have a string literal, and not a # preprocessing token. (Compiler errors are to be expected when using C++11 features. There's not been enough time yet for the implementers to get all of the bugs out.)

like image 99
James Kanze Avatar answered Oct 14 '22 03:10

James Kanze