如何通过 Linux 平台 Delphi 中的 Link 目标文件?

How to Link object file in Delphi over Linux Platform?

我在 Delphi 应用程序中通过 Linux 平台使用目标文件并链接它们,如下面的代码所示并出现错误:

"E2065 不满足转发或外部声明:'add'"

Delphi:

    program ITP_Test;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      System.SysUtils;
    
    {$LINK 'hello.o'}
    
    function add(a ,b : Integer): Integer; cdecl; external;
    
    begin
      Writeln(add(2,7));
    end.

hello.c
    
    #include<stdio.h>
    #ifdef __cplusplus
    extern "C"
    {
    #endif
    int add(int a, int b)
    {
        return a + b;
    }
    #ifdef __cplusplus
    }
    #endif

使用命令编译hello.c:

'gcc -c hello.c'

gcc 版本:7.5.0 Linux 版本:Ubuntu 18.04

我在 Delphi documentation 中找到了解决方案。

您的示例的语法是:

function add(a, b : Integer): Integer; cdecl; external object 'hello.o' name 'add';

无需使用 $LINK 编译器指令。

因此您的示例的完整代码变为:

program LinuxExternalHello;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils;

function add(a, b : Integer): Integer; cdecl; external object 'hello.o' name 'add';

begin
  Writeln(add(2,7));
end.

hello.c编译的方式完全正确

Marion Candau 在 his YouTube video 中描述的替代方案仍然有效,但需要多一步来构建存档文件。