OCaml 动态链接和 -nodynlink 编译标志

OCaml dynamic linking and -nodynlink compilation flag

根据 OCaml User's Manual chapter on ocamlopt:

-nodynlink Allow the compiler to use some optimizations that are valid only for code that is never dynlinked.
...
-shared [...] Under some systems (currently, only Linux AMD 64), all the OCaml code linked in a plugin must have been compiled without the -nodynlink flag. [...]

对我来说,这意味着:

所以我的实际问题有两个方面:

  1. 我上面的解释正确吗?
  2. 当我故意违反上述限制时,compiler/loader/etc并没有给我警告信息。我的错误行为会导致什么样的错误/不良行为?

提前致谢!

第一点是正确的。然而,许多现代操作系统默认使用 PIE 可执行文件,这与 -nodynlink 选项不兼容。

关于你的第二点,在第二个位置指定 -shared 将删除 -nodynlink 标志,这可以解释为什么你没有得到任何错误。否则,对于非空插件,链接器应该生成重定位错误。通常尝试编译

let printer () = Format.printf "I am a plugin@."
let () = Lib.register := printer :: !Lib.register

# ocamlopt -shared -nodynlink plugin.ml -o plugin.cmxs 

给我

/usr/bin/ld: plugin.o: warning: relocation against `camlPlugin__Pfield_51' in >read-only section `.text'
/usr/bin/ld: plugin.o: relocation R_X86_64_PC32 against symbol >`camlPlugin__const_block_11' can not be used when making a shared object; >recompile with -fPIC
/usr/bin/ld: final link failed: bad value