简体   繁体   中英

OCaml: How can I get the path to the *current module* / my project's directory?

I'm new to OCaml, but I'm trying to figure out the equivalent of __filename , __dirname from Node. That is, I need to build a path relative to the file containing the code in question.


For reference, I'm working through Ghuloum's IACC: http://ell.io/tt$ocameel

I'm building my first compiler, and I have an utterly-simplistic 'runtime' file (in C — temporarily ) adjacent to the compiler's source-code. I need to be able to pass the path to this file, as an argument (or a pre-compiled version, I suppose) to gcc or my linker, to have it linked against my compiler's output when I invoke the linker/assembler tooling.

(This may be a stupid question — I'm at a bit of an unknown-unknown here, “how does a compiler get the runtime to the linker”, or something like that. Any commentary about idiomatic solutions to this is welcome, even if it's not a direct answer to the above question!)

If you're running the source file directly via ocaml myfile.ml , Sys.argv.(0) will give you the path to the source file and you can use Filename.dirname to get the directory from that.

If you first compile the source file into an executable and then run the executable, Sys.argv.(0) will give you the name of the executable. In that scenario it's impossible to get the location of the source code (especially if you consider that the person running the executable might not even have the source code on their system).

If you set up your project structure, so that your sources live in src/, your compiled binary in bin/ and the compiled stdlib in lib/, you could just use Filename.dirname Sys.argv.(0) ^ "../lib" as the library path for gcc . This will work whether you run ocaml src/mycompiler.ml , bin/mycompiler or just mycompiler after installing everything to /usr/ or /usr/local/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM