How to compile c++ code at runtime (like eval in Python)?

不羁岁月 提交于 2020-01-06 07:12:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/55387656/how-to-compile-c-code-at-runtime-like-eval-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!