Overloading function in C bindings

It looks like I cannot overload functions in C bindings:

@[Link(ldflags: "#{__DIR__}/tst.o")]
lib LibTst
  fun func=func_f(a : Float32) : Float32
  fun func=func_d(a : Float64) : Float64
end

Furthermore, compiler silently uses first function without any warning. Am I missing something here? What is a recommendation to avoid a lot of boilerplate code defining overloads?

C doesnā€™t have overloads and so the C bindings in Crystal donā€™t have overloads either. When the compiler finds SomeLib.name(...) it just finds the first (only) one with that name and uses it. If you ā€œoverloadā€ it, like you did in the above example, you actually overwrite it.

Youā€™ll have to use func_f and func_d separately.

You could open an issue to try to discuss this, but I donā€™t think it will be changed soon (if at all). Currently the code that checks C function matching is very different compared to regular Crystal code, mainly because for C we autocast some stuff (to_unsafe), C supports untyped splats, etc.

Does it makes sense to show a warning/error if same name is used twice? Or it is impossible due to macros?

This should either be an error, or it should use the second definition, please open an issue.

1 Like