首页 > 解决方案 > 在 Ada 中导入 pragma:GNAT 是如何知道在哪里查找的?

问题描述

getpid我使用此编译指示从 C导入:

function Get_Process_ID return Process_ID;
pragma Import (C, Get_Process_ID, "getpid");

我预计这会更难一些。要getpid在 C 中使用,我需要显式包含头文件 unistd.h;在上面的编译指示中,我没有提到头文件。GNAT 如何准确地知道在哪里可以找到getpid

编辑:

这是一个最小的工作示例:

with Ada.Text_IO;

procedure Main is
   subtype Process_ID is Integer;
   function Get_Process_ID return Process_ID;
   pragma Import (C, Get_Process_ID, "getpid");   
begin
   Ada.Text_IO.Put_Line (Process_ID'Image (Get_Process_ID));
end Main;

保存为 main.adb,使用以下命令编译:

gnat make main.adb

我正在使用gnat来自 Ubuntu 18.04 软件存储库的全新安装包,没有配置或项目文件。GNAT 版本是 7.5.0。

标签: ada

解决方案


A detailed explanation is available in AdaCore's documentation on the GNAT Configurable Runtime Facility. By default, a program compiled with GNAT is linked against libc.a and a few others:

When an Ada program is built, the object code that makes up the final executable may come from the following entities (in addition to the user code itself):

  • GNAT Pro run-time library
  • C library
  • Math library
  • Internal GCC library
  • Startup code

The GNAT and GCC drivers automatically link all these libraries and objects with the final executable, statically or dynamically depending on the target and on some compilation options. The -nostdlib and -nodefaultlibs options may be used to control this automatic behavior.

Compiling my minimum working example with the -nostdlib flag fails with the following error (among many others):

...
main.adb:(.text+0x20): undefined reference to `getpid'
...

Functions provided in libc.a might vary by platform. On Ubuntu, you can find libc.a using locate, and check to see which symbols are defined using nm.


推荐阅读