0

I have 3 C++ files that I would like to generate using an executable file, I mean if I click on the executable my 3 files should appear beside it.

So I thought about using ofstream and then create my three files like this. But the problem is, my 3 files contain a lot of lines and escaping the " and ' will take a lot of time...

How can I embed C++ source code inside my executable without the hassle of escaping the string literals?

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • 9
    Use [raw string literals](http://en.cppreference.com/w/cpp/language/string_literal). – nwp Sep 14 '17 at 14:23
  • But how ? do you have a tutorial ? Thank you – Vicky Harris Sep 14 '17 at 14:28
  • And with string literals is not a good idea because in my code I have a lot of " and if I use the strings I will have a lot of problems for instance if in my code I have `std::string a = "std::cout << "Hello"< – Vicky Harris Sep 14 '17 at 14:33
  • Have a look at https://stackoverflow.com/questions/19638557/read-a-file-into-a-string-at-compile-time. – Mark Ransom Sep 14 '17 at 14:34
  • 3
    @VickyHarris `std::string a = "std::cout << "Hello"< – Algirdas Preidžius Sep 14 '17 at 14:34
  • 1
    Resource-files or `objcopy` on Linux should do the trick. But there really isn't much you could do in a system-independent way apart from embedding the text in the source-file of your program. –  Sep 14 '17 at 14:35
  • @VickyHarris: a [raw string literal](http://en.cppreference.com/w/cpp/language/string_literal) would look more like this: `std::string a = R"mycode(std::cout << "Hello"< – Remy Lebeau Sep 14 '17 at 18:28

1 Answers1

4

If you're on Linux or similar, you can use objcopy to do this easily during your build process:

objcopy --input binary --output elf64-x86-64 myfile.cpp myfiletxt.o

What this does is to create an object file called myfiletxt.o which you can then link into your executable. This object file will contain a symbol which is the entire content of myfile.cpp. You can then print it out etc.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • What's the name of the symbol? Can it be changed? – Quentin Sep 14 '17 at 14:39
  • See https://stackoverflow.com/questions/42235175/how-do-i-add-contents-of-text-file-as-a-section-in-an-elf-file – Garf365 Sep 14 '17 at 14:49
  • @Quentin: in this example the symbols are `_binary_myfile_cpp_{start,end,size}`. I think you can change them using `objcopy --redefine-sym ...`. – John Zwinck Sep 15 '17 at 00:42