Search code examples
cmodelicaopenmodelica

External functions: Calling a C script that use external Library


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


Solution

  • 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