Search code examples
ccompiler-constructioncompiler-theory

Pass Directory Context to Compiler


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"?


Solution

  • 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).