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

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