Dec 1, 2011

Compiling source files: C/C++ vs Java

Each time I switch between C/C++ and Java, I tend to forget the commands to compile the source files. I should make a post that makes sure I reminds (at least I don't forget) the difference between the two.

C/C++:
If I am trying to compile a file called main.cpp and it uses other file such as helperA.c and helperB.c; I would be using the command:
>>g++ -o main.o helperA.c helperB.c main.cpp

This will create an executable called main.o. I can run this executable using:
>>./main.o

Additional note is that C/C++ uses command line arguments in pointer to character array. An integer argc counts the number of arguments. For example,
int main(int argc, char* argv[]) {...
If I run the program using three arguments then argc will be 4 (3 arguments in addition to the name of the program in argv[0]). The first argv[0] will hold the name of the executable. The three arguments that I passed will be stored in argv[1], argv[2], and argv[3] respectively.

Java:
If I am trying to compile a file called Main.java and it uses other file such as HelperA.java and HelperB.java; I would be using the command:
>>javac -d bin -sourcepath src src/Main.java

Here I am assuming that I have the source files inside the directory src. To indicate that I used -sourcepath option. The compiled Main.class, HelperA.class, and Helper.B files will be created inside the folder bin. And I indicated that using the -d option.

Given the above compiled files, I will get inside the bin folder using the cd command. I can run this executable using:
>>java Main

As opposed to the C/C++ command line argument, Java uses only an array of String type. For example,
public static void main(String[] argv) {...
If I run the program using three arguments, then I can access those arguments inside the main by
argv[0], argv[1], and argv[2] respectively. Index in "String[] argv" starts from 0 as opposed to C/C++, which starts at 1 (index 0 there stores the executable name).

Orpheus and Eurydice