How to compile c++ code at runtime (like eval in P

2019-08-17 17:33发布

I'm compiling some C++ code at runtime, which I'm then calling in a sort of plugin system, see also my other question. What I do is I create the source code, write it to a file, compile that file and write the output to another file. However, this process feels kinda ugly so I was hoping for some input.

//Open a file
std::ofstream fout("SOURCECODEPATH");

//Write actual function to file
fout << "extern \"C\" void testFunc(float testArray[]) {\n"
        "    testArray[0] = 1.0;\n"
        "    testArray[1] = 2.0;\n"
        "    testArray[2] = 3.0;\n"
        "}" << std::endl;

//Compile the file, and write the stdout and stderr to PROCESSOUTPUTPATH using "&>"
system("c++ -shared -fPIC -std=c++14 SOURCECODEPATH -o COMPILEDLIBRARYPATH &> PROCESSOUTPUTPATH");

//Read PROCESSOUTPUTPATH (not implemented)

Currently it's creating 3 files, SOURCECODEPATH, COMPILEDLIBRARYPATH, and PROCESSOUTPUTPATH. However, I would much rather not have the SOURCECODEPATH and PROCESSOUTPUTPATH written to the OS, but rather have them used internally. So pipe (?) the sourcecode to the process and get back the output (preferable split into stderr and stdout). What would be the easiest way to do this?

标签: c++ pipe system
1条回答
闹够了就滚
2楼-- · 2019-08-17 18:20

Please reconsider what you're doing. C++ and Python are very different languages in very many ways, not least in their build and execution models. It seems very unlikely that runtime compilation is the real solution to your underlying problem (which you have not shared with us). Simply put, C++ was not designed to support this, Python was.

Technically, there are a few solutions for runtime compilation of C++, but they require much more management and effort than eval in Python. However, they are pretty specialised and, again, unlikely to be a good solution to your underlying problem.

查看更多
登录 后发表回答