如何在OCaml中分离二进制代码与源文件?编译产物存至build目录
Got it! Let's sort this out for you—keeping your source directory clean while sending all build artifacts to the build folder is totally doable with OCamlc, and there are two straightforward ways to handle it:
推荐方法:使用-build-dir参数(批量处理最省心)
OCamlc has a dedicated -build-dir parameter that automatically sends all compilation artifacts (including .cmo, .cmi, .cmt, etc.) to your target directory, so you don't have to set output paths for every single source file.
Here's how to use it:
- First, make sure the
builddirectory exists (create it if not):mkdir -p build - Add the
-build-dir buildflag when compiling your source files:
This will automatically generateocamlc -build-dir build -c file1.ml ocamlc -build-dir build -c file2.ml # Repeat this for all your .ml source filesfile1.cmo,file1.cmi,file2.cmo,file2.cmi, etc., directly inside thebuilddirectory. - When linking to create the executable, pull the
.cmofiles from thebuilddirectory and specify the output path there too:ocamlc -o build/main build/file1.cmo build/file2.cmo
备选方法:手动指定单个文件的输出路径
If you only have a small number of source files to handle, you can also explicitly set the output path for each .cmo using the -o flag with the -c command:
- Again, create the
builddirectory if it doesn't exist:mkdir -p build - Compile each source file, specifying exactly where to save the
.cmo:ocamlc -c file1.ml -o build/file1.cmo ocamlc -c file2.ml -o build/file2.cmo - Link the executable using the
.cmofiles from thebuilddirectory:ocamlc -o build/main build/file1.cmo build/file2.cmo
Quick Tip
- The
-build-dirparameter is fully supported in OCaml 4.08 and later, and it's the cleanest way to manage your build artifact directory. - Keeping intermediate files out of your source directory makes it easier to maintain a tidy project structure—you can even clean all build artifacts at once by deleting the
buildfolder.
内容的提问来源于stack exchange,提问作者Pierre-olivier Gendraud
相关产品推荐
相关产品推荐

