1

I have gone through various questions on the internet to execute a cpp file from python or another cpp file, however, I faced some issues that I would like to share.

Case 1.

a) When I try to run a cpp file from python as described here, I get this error hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] The system cannot find the file specified. However, a.out is created inside the same directory but it still says no file found.

Case 2.

a) When I try to run .cpp file from another cpp file as described here, I don't get an error but let's say I want to run a.cpp from b.cpp so first I need to build a.exe and then call system("a.exe") from b.cpp code, but I want something as shown below since I don't want to manually create an executable file for a.cppevery time.

// b.cpp
method("a.cpp");
OR
command to create a.exe 
system("a.exe") 
kuspia
  • 55
  • 8
  • What do you mean by "execute a cpp file"? C++ code is not executed, it is compiled and linked with other C++ code to produce an executable. Are just trying to call a function defined in another `.cpp` file? Can you show [mcve] of what you are trying to achieve? – Yksisarvinen Apr 04 '22 at 08:06
  • You can't "run" or "execute" C++sourc files. Source files must be built and linked into an executable program before you can run the generated executable. If you want to avoid rebuilding every time, perhaps use a tool such as Make to build and execute? – Some programmer dude Apr 04 '22 at 08:06
  • c++ is a compiled language, you can't avoid creating an executable – Alan Birtles Apr 04 '22 at 08:06
  • 1
    With that said, there do exists a couple of C++ *interpreters* which can compile and link C++ source files in memory, and run them from memory. – Some programmer dude Apr 04 '22 at 08:08
  • @Yksisarvinen I am replicating the same thing https://stackoverflow.com/a/58422966/13248217 as described here, I am not calling any function defined in another ```.cpp``` file – kuspia Apr 04 '22 at 08:10
  • ok, I understood everyone's point but how can I build an executable file for a ```.cpp``` file from some c++ code, in other words, I want to write a c++ program that build a ``` .exe``` file of another ```.cpp``` file. – kuspia Apr 04 '22 at 08:25
  • you would have to learn how to use C/C++ compiler. Basic command is (on Linux) `gcc a.cpp -o a.exe` but if it needs some modules then you have to add them as parameters in this command. And if it uses many files .cpp then it may need to use compiler on every file separatelly. And later it may need also program `link` to join it with libraries. If you repeate it for the same file then you may put all rules in file `makefile` and execute all with command `make`. And some IDEs works this way - they generate `makefile` and runs `make` – furas Apr 04 '22 at 10:58

0 Answers0