简体   繁体   中英

How to include file in code (not in header) c++

#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

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.

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

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-cc-and-the-likes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM