Search code examples
modelica

Modelica external functions: C versus C99


In Modelica it is possible to define external functions.
Chapter 12.9 of the spec says C and Fortran77 are supported,
C++ and Fortran90 might be supported in the future.
Now I wonder which versions of C are supported?

In particular I need the logarithmic gamma function which is available in C99, so I tried the following:

function lgamma "logarithmic gamma function"
  input Real u;
  output Real y;
external "C" y = lgamma(u);
end lgamma;

but it does not work, while powf works:

function powf "power function a^b"
  input Real a;
  input Real b;
  output Real y;
external "C" y = powf(a,b);
end powf;

This probably happens because powf is available in C while lgamma was introduced in C99.
But is this a limitation of Modelica, Dymola or of my compiler?
Is there a way to get C99 external functions to work?
On the Wikipedia list of C mathematical operations there are some more interesting function like error function erf and erfc, these would also be nice to have.


Solution

  • You can only assume that C89/90 code compiles in a Modelica compiler. This is mainly concerning syntax though (if you use Include annotations or Library="file.c").

    The functions that are available mainly depend on the C library that your compiler links against. I guess Microsoft's C library does not contain lgamma, so it cannot be linked against. On Linux/OpenModelica, the lgamma example does work as libm contains the function (it's compiling using c90 mode, but implicitly adding a double lgamma(double) declaration).

    The powf example also compiles, but does not work correctly since your external "C" declaration states that it uses double precision floating point (and you cannot change this as of Modelica 3.2). powf will read half of a and use it as its first argument, then read the second half of a and use it as its second argument. b would be discarded. If you set the compiler flags to std=c99, the error is detected:

    powf.h:23:15: error: conflicting types for ‘powf’

    Note that if you use Dymola on Windows, you are most likely using Visual Studio. In that case, there is no C99 support except the parts that were copied from C++.