krishkule
krishkule

Reputation: 79

Can i compile a c++ file within a c++ file execution without any extra programs or installations?

I was reading on Clang and Ch (c++ interpreters), but its not clear for me, is it possible to run a newly generated .cpp file without any installations? Because i need to run the final program on any pc...

ps. if yes, does anyone have a good example, where a .cpp file is being executed within c++ code?

Upvotes: 2

Views: 289

Answers (3)

Shopner Jhuri
Shopner Jhuri

Reputation: 33

As far as I know, it is impossible, because compilation process of a CPP file is like this-

  1. Preprocessing: the preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.

  2. Compilation: the compiler takes the pre-processor's output and produces an object file from it.

  3. Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.

So, there should be intermediate files and executable files.

More can be found here-

https://stackoverflow.com/a/6264256/7725220

Upvotes: 2

kuba
kuba

Reputation: 7389

This is probably impossible or at least very hard. You would have to include the whole compiler (including linker, assembler, optimizer, preprocessor, ...) inside your program and that would make it extremely big.

One way of doing this is with Clang (as you already noted), there is even a demo project called "Clang interpreter" in the source: http://llvm.org/viewvc/llvm-project/cfe/trunk/examples/clang-interpreter/

However I once tried to compile this "beast" into my program and gave up halfway, because the file size of the result binary (or binaries with external libraries) gets into tens of megabytes (maybe even a hundred).

My suggestion is to either produce a different script (e.g. bash/sh script, which you could execute on any unix machine) that can be interpreted easily.

Upvotes: 3

Šimon Tóth
Šimon Tóth

Reputation: 36451

Kind of depends on what you mean by "installations".

Yes you can distribute your program with a full compiler, compile the source code and then execute the final result (all from the original exe).

Upvotes: 0

Related Questions