0
#include <iostream  
#include <string  
#include <fstream>  
using namespace std;

int main() {  
    string file = "mycode.h";  
    #include file  
}

I want to include some code from another file but to user can type location of file than code to be used

8
  • 5
    #include instructions are executed at compile time so this will not work Commented Dec 15, 2020 at 20:12
  • is there any other way to do this? Commented Dec 15, 2020 at 20:19
  • @H2102M It depends what is in mycode.th. Is it just data, or is it actual code? Commented Dec 15, 2020 at 20:20
  • @0x5453 it is code Commented Dec 15, 2020 at 20:22
  • 3
    If you want to interpret code at runtime, I would recommend that code to be something else than c++. Choosing another language will give you many more options for interpreters that can be embedded into your program. Commented Dec 15, 2020 at 20:32

3 Answers 3

2

This is not possible.

C++ has to be compiled to convert the source code into executable code. #include is a preprocessor command, which is executed at an early compilation stage to combine different source files into a single file that is further processed by the compiler.

The final executable file contains so-called machine-code that is specific for a CPU and an operating system, but in general it does not contain the source code (except maybe for debugging purposes).

Maybe you can solve your problem by an external control program that the user runs and that receives the include path as input, inserts it into the source code, calls the compiler, and executes the compiled executable.

Sign up to request clarification or add additional context in comments.

Comments

0

For dynamic include in C++ I think you may need a C++ interpreter. There's one, called Cling:

https://root.cern/cling/

https://github.com/root-project/cling

Comments

0

You are asking for JIT compilation; I think CLing can work for you: https://github.com/root-project/cling

if you check the documents you will see it is doing what you are asking,

ref: https://softwareengineering.stackexchange.com/questions/29344/jit-compiler-for-c-c-and-the-likes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.