Tuesday, March 24, 2015

Dual-Compiling Code

While working with Assembly (using TASM), I realized that the semicolon, which is used for comments, is just the end of a statement in C++ (and Java, of course, amongst others). In addition, you can comment blocks of code out in C++/Java quite easily. The question, then, became whether or not it was possible to write one program to be read differently by both languages - where one language is commented out in the other, provided the file extension is appropriate. I decided to use "Hello World" as a proof of concept - though I later had to switch from C++ to Java, because you need to #include <iostream> in C++, but you can't have any statements before the preprocessor, which you need to have to use comments in Assembly. Java doesn't require any includes to print to the screen.

You could do about anything like this, though it would be quite useless and none too pretty to read. I'm not quite sure if this would work with any other languages, either - though I'm interested to see if you could cram three or four in one file.

This code is as follows:

; /*Hello World
; For fun!*/public class HloWrld/*
.MODEL SMALL
.STACK 100H
.DATA
Greeting db 'Hello world!',13,10,'$'
.CODE;*/{
;public static void main(String[] args) {
;/*
MAIN PROC
; Initialize DS register
mov ax,@data ; initialize data segment address
mov ds,ax ; initialize ds
; display message using DOS function
;*/System.out.println("Hello world!");
;/*
mov ah,9 ; print string function
mov dx,offset Greeting ; DS:DX points to string
int 21h
;*/}/*
; Exit
mov ah,4ch
int 21h
main endp
end MAIN
;*/}
view raw HloWrld.java hosted with ❤ by GitHub