This article is part of the Batchography articles series and today, I am going to show you how to write a valid Batch file that is also a valid C/C++ file. The Batch file part of the source can do anything, however in this article, its sole purpose will be to compile itself and run the compile C++ program.
Let’s get started with the Polyglot source code:
- Line 1 is the first point of execution. We have no choice but to use a proper C++ syntax otherwise the C++ compiler will fail. The Batch file interpreter is much more forgiving, hence, we start the file with the multi line comment: “/*”. The “/*” is not a valid Batch command but we can swallow the error and redirect it to NUL.
- Optionally, on the first line, we can use a trick to echo the backspace character (ASCII code 0x08) in order to hide the first command’s ECHO (note: print lots of spaces after this command to hide the first command that was not ECHOed off).
- At Line 2, we directly turn off the command echo.
- Line 3 is optional and is used to localize all the environment variable changes during the execution of this Batch file.
- From line 5 and onwards you can write any Batch script syntax safely.
- Lines 11 to 22 basically invoke the Microsoft’s C/C++ compiler (cl.exe) to compile the Batch script, check the result of the compilation, execute the compiled program and cleanup.
- Line 23 closes the multi-line comment opened at Line 1.
- Technically speaking, from Line 25 and onwards is where the real C++ program starts.
That’s it! A self-compiling C++ program written in Batch file.
Please note that the Batch part script assumes that the C/C++ Microsoft compiler (cl.exe) is in the PATH environment variable. If not, you will have to write some extra Batch file code to detect the compiler path.
For simplicity, if you have Visual Studio installed, I advise you to try this Batch file by opening a “Developer Prompt”:
As you can see from the output, the C++ portion has been compiled and executed!
You can download the script from the Batchography’s book source code repository here: https://github.com/PassingTheKnowledge/Batchography/blob/master/batch-cpp.bat
Do you want to master Batch Files programming? Look no further, the Batchography is the right book for you.
You might also like:
- Batchography: How to “switch/case” in Batch files
- Detect executable format using Python
- Batchography: Embedding Python scripts in your Batch file script
- Batchography: Converting numbers to characters (or the CHR() function)