我喜欢我的库同时作为可执行文件。期望的行为是:
$ ./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.
当我编译scriptedmain。p与fpc 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.
当我编译测试。p和fpc test.p
,结果可执行文件结合了两个begin
/end
声明(不是期望的行为)。
$ ./test
Main: The meaning of life is: 42
Test: The meaning of life is: 42
我不知道你使用的Pascal是什么味道,但是一些变体支持{$IFC condition} ... {$ENDC}
的条件编译。您可以将它与编译时定义结合使用,以包含/排除给定版本中需要或不需要的代码。
感谢Free Pascal邮件列表中的Ager和Zhirov,我能够用最少的技巧构建一个工作的脚本主示例。也发在RosettaCode
Makefile:
all: scriptedmain
scriptedmain: scriptedmain.pas
fpc -dscriptedmain scriptedmain.pas
test: test.pas scriptedmain
fpc test.pas
clean:
-rm test
-rm scriptedmain
-rm *.o
-rm *.ppu
scriptedmain.pas:
{$IFDEF scriptedmain}
program ScriptedMain;
{$ELSE}
unit ScriptedMain;
interface
function MeaningOfLife () : integer;
implementation
{$ENDIF}
function MeaningOfLife () : integer;
begin
MeaningOfLife := 42
end;
{$IFDEF scriptedmain}
begin
write('Main: The meaning of life is: ');
writeln(MeaningOfLife())
{$ENDIF}
end.
test.pas:
program Test;
uses
ScriptedMain;
begin
write('Test: The meaning of life is: ');
writeln(MeaningOfLife())
end.
的例子:
$ make
$ ./scriptedmain
Main: The meaning of life is: 42
$ make test
$ ./test
Test: The meaning of life is: 42