Pascal 单位可以编译为可执行文件吗?
我喜欢我的库兼作可执行文件。所需的行为是:
$ ./scriptedmain
Main: The meaning of life is: 42
$ ./test
Test: The meaning of life is: 42
我怎样才能:
- 将
scriptedmain.p
编译成scriptedmain
二进制文件? - 阻止
test.p
运行scriptedmain.p
的begin
/end
部分中的代码?
scriptedmain.p:
unit ScriptedMain;
interface
function MeaningOfLife () : integer;
implementation
function MeaningOfLife () : integer;
begin
MeaningOfLife := 42
end;
begin
write('Main: The meaning of life is: ');
writeln(MeaningOfLife())
end.
当我使用 fpc scriptedmain.p
编译 scriptedmain.p 时,没有创建可执行文件,因为 Pascal 检测到它是一个单元。但我希望它除了库之外还可以是可执行文件。
$ ./scriptedmain
-bash: ./scriptedmain: No such file or directory
test.p:
program Test;
uses
ScriptedMain;
begin
write('Test: The meaning of life is: ');
writeln(MeaningOfLife())
end.
当我使用 fpc test.p
编译 test.p 时,生成的可执行文件结合了两个 begin
/end
声明(而不是期望的行为)。
$ ./test
Main: The meaning of life is: 42
Test: The meaning of life is: 42
I like my libraries to double as executables. The desired behavior is:
$ ./scriptedmain
Main: The meaning of life is: 42
$ ./test
Test: The meaning of life is: 42
How can I:
- Get
scriptedmain.p
to compile into ascriptedmain
binary? - Prevent
test.p
from running the code that's inscriptedmain.p
'sbegin
/end
section?
scriptedmain.p:
unit ScriptedMain;
interface
function MeaningOfLife () : integer;
implementation
function MeaningOfLife () : integer;
begin
MeaningOfLife := 42
end;
begin
write('Main: The meaning of life is: ');
writeln(MeaningOfLife())
end.
When I compile scriptedmain.p with fpc scriptedmain.p
, no executable is created, because Pascal detects that it's a unit. But I want it to be an executable in addition to a library.
$ ./scriptedmain
-bash: ./scriptedmain: No such file or directory
test.p:
program Test;
uses
ScriptedMain;
begin
write('Test: The meaning of life is: ');
writeln(MeaningOfLife())
end.
When I compile test.p with fpc test.p
, the resulting executable combines the two begin
/end
declarations (NOT the desired behavior).
$ ./test
Main: The meaning of life is: 42
Test: The meaning of life is: 42
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道您使用的 Pascal 是什么风格,但某些变体支持使用
{$IFC condition} ... {$ENDC}
进行条件编译。您也许可以将其与编译时定义结合使用,以包含/排除给定版本中需要或不需要的代码。I don't know what flavour of Pascal you're using but some variants support conditional compilation with
{$IFC condition} ... {$ENDC}
. You could perhaps use this in conjunction with a compile time define to include/exclude code that you need or don't need in a given version.感谢 Free Pascal 邮件列表中的 Ager 和 Zirov,我能够用最少的技巧构建一个工作脚本化的主要示例。还发布在 RosettaCode 上。
Makefile:
scriptedmain.pas:
test.pas:
示例:
Thanks to Ager and Zhirov in the Free Pascal mailing list, I was able to construct a working scripted main example with minimal hacks. Also posted on RosettaCode.
Makefile:
scriptedmain.pas:
test.pas:
Example: