简体   繁体   中英

How to compile a C++ source code via C++

Can we write a program in c++ that compile a c++ source code using a compiler ?

for example we have a program that takes the file name and then compiles it:

Enter your C++ source code file name : cppSource.cpp
your program compiled. 
output: cppSource.exe

Or:

Enter your C++ source code file name : cppSource.cpp
Sorry. There is no C++ Compiler in your computer.

I do not mean that we write a Compiler. I mean write a program that compiles the cpp file using a compiler. How can we access a compiler. and how to detect that in a computer a compiler is installed or not.

Use system function to call any executable, for example g++ compiler:

#include <stdlib.h>
int retval = system("g++ file.cpp");

Return value of system can be checked, and it will be the return value of the called executable if the shell was able to execute it. In this case, usually it will be 0 if a compiler exists and the code compiled successfully.

Alternatively (and also to prevent called program output from being displayed), for additional details, it would be possible to redirect the program output to a file and then open that file and parse it's content.

int retval = system("g++ file.cpp > output.txt");

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