我想从 Ada 代码创建静态库并将其部署到没有 GNAT 工具链的开发人员(用于 C/C++ 代码)。
当我尝试将 Ada-Library ('.a') 与 C 程序链接时,我会遇到以下链接器错误:
undefined reference to `__gnat_rcheck_CE_Overflow_Check'
undefined reference to `ada__text_io__put_line__2'
我怎样才能做到这一点?它接缝我应该链接到运行时库,但是如何?
测试代码:
主.c:
#include <stdio.h>
extern void adaTest();
extern int add5(int);
int main(){
adaTest();
int b = add5(2);
printf("--> %d \ndone.\n", b);
return 0;
}
ada_lib_project.gpr:
library project ada_lib_project is
for Languages use ("Ada");
for Library_Name use "My_Ada_Lib";
for Library_Dir use "my_generated_lib";
for Library_Kind use "Static";
end ada_lib_project;
adatestpacket.ads:
with Interfaces.C; use Interfaces.C;
package adatestpacket is
procedure adatest with
Export, Convention => C, External_Name => "adaTest";
function add5(x: in int) return int with
Export, Convention => C, External_Name => "add5";
end adatestpacket;
adatestpacket.adb:
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C; use Interfaces.C;
package body adatestpacket is
procedure adatest is
begin
Put_Line("This is executed ADA/SPARK-Code...");
null;
end adatest;
function add5(x: in int) return int is
begin
return x + 5;
end add5;
end adatestpacket;
编译:
gcc -c main.c -o main.o # .c -> .o
gprbuild -P ada_lib_project.gpr # .ad[sb] -> .a
gcc main.o -L my_generated_lib -l My_Ada_Lib -o a.out # Linking -- with undefined References
最佳答案
可能最简单的方法是简单地也用 gprbuild 编译 C 源代码(即使你不能在你的目标场景中这样做,你可以做测试并用 -v
查看 GPRbuild 对让它工作):
with "ada_lib_project";
project My_Executable is
for Languages use ("C");
for Main use ("main.c");
end My_Executable;
您还需要调用 adainit
和 adafinal
初始化/完成 Ada 包:
#include <stdio.h>
extern void adainit();
extern void adafinal();
extern void adaTest();
extern int add5(int);
int main(){
adainit();
adaTest();
int b = add5(2);
printf("--> %d \ndone.\n", b);
adafinal();
return 0;
}
adainit
和 adafinal
由 gnatbind
生成对于独立库。当看到您使用 C 可执行文件中的 Ada 库时,我不完全确定 GPRBuild 是否会处理这个问题;如果没有,你将需要
package Binder is
for Default_Switches ("Ada") use ("-n");
end Binder;
在你的图书馆。这样做之后,你应该可以做到
gprbuild my_executable.gpr
如果你想在没有 GPRbuild 的情况下进行,-n
/adainit
/adafinal
部分仍然适用,您需要将您的可执行文件链接到
-l<your-gnat-lib>
其中 gnat-2021
.您可能需要添加 -L<directory-containing-that-lib>
取决于它所在的位置。
(这个答案可能有错误,因为我目前在 M1 上无法测试它)
编辑:如果您真的想为开发人员提供无法访问 GNAT 的权限,您需要构建一个封装,即动态库。 This answer涵盖了那个过程。如果需要提供静态库,您必须至少提供 GNAT 标准库文件。
关于gcc - 创建一个无需 gnat-tools 即可链接的静态 Ada-Library,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70020795/