helloworld95
helloworld95

Reputation: 396

Can you compile C++ within a Python script?

I'm VERY new to C++. I'm writing a Python script to compile and call a C++ program. The code:

system( "g++ -std=c++11 /home/my_program.cpp" )
system( "/home/a.out arg1" )

This seems to execute the C++ program just fine.

However, when I make changes to the C++ program and try running my pythons script, the changes don't seem to take effect. The output of the C++ code is still the same as it was before the changes.

Is it possible to compile C++ code in Python?

Upvotes: 0

Views: 635

Answers (1)

parktomatomi
parktomatomi

Reputation: 4079

That binary is going to drop in the working directory, not next to the C++ file. Add a -o argument to g++ to make sure it writes to the same place. When I try your example myself with the output option, it works just fine.

For a more literal interpretation of your question, check out cppyy: https://cppyy.readthedocs.io/en/latest/

import cppyy
cppyy.cppdef(r'void say_hello() { std::cout << "Hello!\n"; }');
cppyy.gbl.say_hello()

Upvotes: 2

Related Questions