How to create a static library from an Ada source that can be called with C ++ code?

I need to create a static library with a bunch of code written in Ada that can be called from code written in C / C ++.

I searched through the Internet and gained some knowledge about gnatmake, gnatbindand gnatlink, but still can not do the job correctly.

Also, I read that there are tools that rely on some kind of project file. I'm not interested in this, I just need to write some commands to write to Makefile.

+4
source share
2 answers

This answer assumes that you are using the GCC toolchain.

, Ada (, ++). gnatbind - , , -L:

-Lxyz     Library build: adainit/final renamed to xyzinit/final, implies -n
[...]
-n        No Ada main program (foreign main routine)

Ada foo.ads,

package Foo is
   procedure Impl
   with
     Convention => C,
     Export,
     External_Name => "foo";
end Foo;

, Ada Ada2012,

package Foo is
   procedure Impl;
   pragma Export (Convention => C, Entity => Impl, External_Name => "foo");
end Foo;

foo.adb,

with Ada.Text_IO;
package body Foo is
   procedure Impl is
   begin
      Ada.Text_IO.Put_Line ("I am foo");
   end Impl;
begin
   Ada.Text_IO.Put_Line ("foo is elaborated");
end Foo;

bar.ads, bar.adb (s/foo/bar/g).

:

gnatmake foo bar

Bind:

gnatbind -Lck -o ck.adb foo.ali bar.ali

( ck.ads, ck.adb, , ).

:

gnatmake ck.adb

:

ar cr ck.o foo.o bar.o

.

C

#include <stdio.h>

void ckinit(void);
void foo(void);
void bar(void);

int main()
{
  ckinit();
  printf("calling foo:\n");
  foo();
  printf("calling bar:\n");
  bar();
  return 0;
}

( ++, extern "C" {..., ).

,

gcc main.c libck.a

. , libck Ada. (macOS), ,

gcc main.c libck.a /opt/gnat-gpl-2016/lib/gcc/x86_64-apple-darwin14.5.0/4.9.4/adalib/libgnat.a

( gcc --print-libgcc-file-name)

:

$ ./a.out
bar is elaborated
foo is elaborated
calling foo:
I am foo
calling bar:
I am bar
+7

! , Makefile:

ada_libs := -lgnat -lgnarl

cpp_src := ...
ada_src := ...

library.so : $(cpp_src:.cc=.o) adalib.a
    g++ -o $@ $^ $(ada_libs)

$(cpp_src:.cc=.o) : %.o : %.cc
    g++ -c -o $@ $<

$(cpp_src:.cc=.d) : %.d : %.cc
    g++ -MM -MF $@ $^

$(addprefix objects/,$(ada_src:.adb=.o)) : objects/%.o : %.adb
    gnatmake -c -D objects $^

adabind.adb : $(addprefix objects/,$(ada_src:.adb=.o))
    gnatbind -n -o $@ $(^:.o=.ali)

adabind.ali : adabind.adb
    gnatmake -c -D objects $^

adalib.a : adabind.ali
    ar cur $@ $(^:.ali=.o) objects/*.o

include $(cpp_src:.cc=.d)

, extern "C" ++.

, , ada (-lgnat -lgnarl) .

+2

Source: https://habr.com/ru/post/1662298/


All Articles