在 Pascal 中的另一个文件夹上使用单元

Use unit on another folder in Pascal

我想要 /project/functions /project/src 这样的结构。我会有一个单位 /project/functions/helloUnit.pas 类似于:

unit helloUnit;
interface
implementation
uses classes;
procedure helloWorld(output);
begin
  writeln('Hello, World');
end.

还有一个文件 /project/src/main.pas 如:

uses helloUnit;
Begin
  helloWorld;
End.

我一直在努力让它发挥作用,但还没有找到方法。我在 linux 命令行上使用 fpc 编译器,以防我没有定义路径或其他东西。

您的示例代码存在一些问题,修复这些问题会很有帮助 在尝试从命令行编译它之前。

首先,您需要一个 fpc 的项目文件来编译生成您的程序。为了这, 我在项目文件夹中创建了这个文件并将其命名为 hello.lpr:

program Hello;

uses
  hellounit,
  main;

begin
  HelloWorld;
end.

然后更正Main.Pas如下:

unit main;

interface

uses helloUnit;

procedure SayHello;

implementation

procedure SayHello;
Begin
  helloWorld;
End;
End.

请注意,procedure SayHello; 已添加到界面部分,并且 End; 已添加到程序声明的末尾。 End. 告诉 编译器已到达单元中源代码的末尾。

接下来正确的helloUnit如下

unit helloUnit;

interface

procedure helloWorld;

implementation

uses classes;

procedure helloWorld;
begin
  writeln('Hello, World');
end; {added}

end.

现在在projects文件夹下写一个批处理文件CompileHello.Bat(假设Windows) 含

D:\Lazarus2\fpc.0.4\bin\i386-win32\fpc -Fufunctions;src hello.lpr

然后 运行 从项目文件夹中的 CMD 提示符。 -Fu 编译器开关告诉 fpc 在哪里可以找到与项目不在同一文件夹中的单元 文件。 -Fu 之后的路径可以相对于项目文件夹。如果你 按照上面的步骤应该编译成功了。

如果您使用的是 Lazarus,fpc 的伴侣 IDE,那么至少有两种方法可以满足您的要求。

  1. 在 IDE 中打开 HelloUnit,使用 View |从 IDE 的菜单中将编辑器文件添加到项目以将 HelloUnit 添加到项目中。这可能是最好的方法,因为它明确地标识了项目的 HelloUnit。

  2. 使用Project | 将HelloUnit.Pas所在的文件夹添加到项目的源路径中选项,然后在弹出窗口中的“编译器选项”下,将文件夹添加到 RHS 上的“其他单元文件”框中。