I'm writing a Java compiler in C just as a recreational project. But, I've noticed that when we compile files in the command line, such as "gcc example.c", the compiler is able to find example.c in the working directory of the terminal without error. How does the compiler know what directory to search example.c for? Does OS find example.c in the directory for the compiler? Also, how may I emulate this action in my C program so that the user can compile their java program from any working directory by calling my compiler such as: "compiler example.java"?
-
3This is a strange question. By default, all the library file open (fopen, open) will interpret relative paths with respect to the shell's current directory. This is just what the C compiler does. Therefore, you don't need to do anything special to get basic C/java compiler behavior. Just pass the filename as-given to fopen(). Things get a bit more complicated when you want to cause your compiler to honor alternate directory specs (like C compiler -I and -L) and search paths (like java CLASSPATH).Gene– Gene2015-09-22 00:15:59 +00:00Commented Sep 22, 2015 at 0:15
2 Answers
fopen will treat relatives paths as relative to the current directory, not the directory where the executable resides. This is the same with most (or even all) file handling function in most other languages.
So to emulate the behaviour of the Java compiler, all you need to do is to iterate over the file names in argv, fopen(the_file_name), generate code for that file, then fopen(class_file_name, "wb") (where class_file_name is file_name with .java replaced by .class) and write the generated bytecode to that.
Getting the full path of the current directory is neither necessary nor helpful. Note that if you just appended each argument to the current directory name, the code would break for absolute paths, whereas simply doing nothing will do the correct thing both for relative and for absolute paths.
2 Comments
fopen looks in the current directory, not in the directory of the executable.If I understand correctly, you need to obtain the full path of the current working directory. There is a POSIX function getcwd (on Windows _getcwd) that can be used to retrieve current working directory of your program.
Then it should be simple to search this directory and find your sources (if they are present).