External functions: Calling a C script that use external Library

Viewed 233

I am trying to call an external C code that use GLPK (GNU Linear Programming Kit) within my Modelica model. The C code works just fine, have tested it in a stand alone mode where all the inputs are self-supplied. When I tried to link it with my Modelica model, it starts to give me linker-type error, that is similar to below:

examples.SimpleSystemOptimalDispatch_functions.c:(.text+0x99d): undefined reference to `glp_set_row_bnds'

I notice that to run the C code in a stand alone mode, a special linker has to be used

gcc standalonecode.c -lglpk -o standalone

I believe the problem is in linking process, but I fail to grasp how to tell Modelica to do the link automatically. Any idea how to solve this linking problem in Modelica?

Thank you and best wishes

2 Answers

You didn't use a special linker. The -lglpk just told the linker to link your executable with the glpk library (libglpk).

Now, Modelica has a usability problem - many of them - and the fact that there's no simple way of just telling Modelica "here's my C file, here's my dynamic library I need, have a go at it" is just the harbinger of worse things ahead.

What you have to do instead is to compile your code to a dynamic library, and then this dynamic library will transitively pull in the libglpk dependency.

g++ -fPIC -shared -lglpk -o libmyCode.so myCode.c

I managed to solve the problem.

What I did was:

  1. Compile the glpk.h located in /usr/local/include/ using
gcc -c glpk.h -o libglpk.o
  1. Using @ReinstateMonica answer, I made my .c file into .so
gcc -fPIC -shared -lglpk -o liblinprog.so st_linprog.c
  1. In my function.mo in my Modelica, I put annotation as follow
annotation(Library ={"linprog","glpk"},
           LibraryDirectory="modelica://SolarTherm/Resources/Include/lib");

What I understood is that since my st_linprog.c is depending on libglpk, then in order for Modelica to be able to run using libglpk, I have to compile glpk.h and convert st_linprog.c to shared library. During the st_linprog.c conversion into shared library, -lglpk flag makes sure that the shared library is linked to libglpk (I think).

If you guys have more elegant approach kindly share it here! Cheers,

Phil

Related