Quantcast
Channel: Wardy's Projects
Viewing all articles
Browse latest Browse all 70

[Ada Example #1] Statically linking C code into an Ada program

$
0
0
The following is intended to be a simple "hello world" style example of how to call a C function from Ada code.  I am using Linux (Debian Jessie, with the latest and greatest GCC v4.9.3 / Gnat v4.9.2 installed).

The C code and the Ada code are compiled separately and linked statically afterwards.

triple.c contains the C function I want to call from Ada...
//-----------------
#include <stdio.h>

int triple(int value)
{
  return value * 3;
}
//-----------------

test_prog.adb contains the Ada main program that calls the triple() function...
-----------------------------------------
with Ada.Integer_Text_IO, Ada.Text_IO;
use Ada.Integer_Text_IO, Ada.Text_IO;

procedure Test_Prog is
   type SInt32 is
      new Integer range -2_147_483_648 .. 2_147_483_647;

   function Triple (value : SInt32) return SInt32;
   pragma Import (C, Triple, "triple");

   A : SInt32 := 123;
   B : SInt32 := 0;
begin
   B := Triple (A); --  call the C function
   Put ("B is ");
   Put (Integer (B));
   Put_Line ("");
end Test_Prog;
-----------------------------------------


Makefile
all:
        gcc -c triple.c
        gnatmake -gnaty -c test_prog.adb
        gnatbind test_prog.ali
        gnatlink test_prog.ali triple.o

clean:
        -rm -f *.ali *.o b~*


It is also possible to do this the other way around - calling an Ada function from a main program written in C, but I suspect that this is a less common method.  The Ada program calls the C function and prints the correct result of 369.  Interestingly, the pragma Import lets you change the capitalisation on "Triple" which allows normal naming conventions in both C and Ada to be preserved.



Viewing all articles
Browse latest Browse all 70

Trending Articles