You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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:

  1. First, make sure the build directory exists (create it if not):
    mkdir -p build
    
  2. Add the -build-dir build flag when compiling your source files:
    ocamlc -build-dir build -c file1.ml
    ocamlc -build-dir build -c file2.ml
    # Repeat this for all your .ml source files
    
    This will automatically generate file1.cmo, file1.cmi, file2.cmo, file2.cmi, etc., directly inside the build directory.
  3. When linking to create the executable, pull the .cmo files from the build directory 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:

  1. Again, create the build directory if it doesn't exist:
    mkdir -p build
    
  2. 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
    
  3. Link the executable using the .cmo files from the build directory:
    ocamlc -o build/main build/file1.cmo build/file2.cmo
    

Quick Tip

  • The -build-dir parameter 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 build folder.

内容的提问来源于stack exchange,提问作者Pierre-olivier Gendraud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:41:51