小试fpc交叉编译:从Linux到Win32

来源:互联网 发布:淘宝鹊桥活动佣金插件 编辑:程序博客网 时间:2024/04/29 18:48
刚刚小小的试了下,程序是一个简单的dll外加一个 调用它的exe。(需要装上这个才能编译:fpc-crosswin32_2.0.4-060919_i386.deb)这两段简单的程序如下。

app.pas

 1 program app;
2
3 { app use win32lib.dll }
4
5 procedure SaySomething(str:PChar);stdcall;external 'win32lib' name 'SaySomething';
6 function Add(a,b:Integer):Integer;stdcall;external 'win32lib' name 'Add';
7
8 var
9 a,b:Integer;
10 begin
11 SaySomething('Enter 2 integers:');
12 Readln(a,b);
13 Writeln(a,'+',b,'=',Add(a,b));
14 end.

win32lib.pas

 1 library win32lib;
2
3 { demo library for win32 }
4
5 procedure SaySomething(str:PChar);stdcall;
6 begin
7 Writeln(str);
8 end;
9
10 function Add(a,b:Integer):Integer;stdcall;
11 begin
12 Add:=a+b;
13 end;
14
15 exports
16 SaySomething,
17 Add;
18 begin
19 end.

程序没什么好说的,编译的时候带上-Twin32参数就行了。然而,在成功连接成DLL之后,会出现一个错误。这个错误我个人估计100%是bug。
stlxv@stlxvcomputer:~/samples/freepascal/win32_dll$ fpc -Twin32 win32lib.pas 
Free Pascal Compiler version 2.0.4 [2007/02/02] for i386
Copyright (c) 1993-2006 by Florian Klaempfl
Target OS: Win32 for i386
Compiling win32lib.pas
Linking win32lib.dll
/usr/bin/fpc-i386-win32-dlltool: Unable to open object file:
win32lib.pas(19,1) Error: Error while linking
Error: /usr/bin/ppc386 returned an error exitcode (normal if you did not specify a source file to be compiled)
写句出错的话不要紧,要紧的是,整个fpc的返回值不是0。假如在Makefile中,这将导致整个make过程的失败。

对于这个问题,有个仁兄写了个wrapper来解决。也正式这篇文章让我有欲望来写这一篇东西。
 1 { 程序来自:
2 http://www.lazarus.freepascal.org/index.php?name=PNphpBB2&file=viewtopic&p=15839
3 这位兄弟同时把fpc-i386-win32-dlltool改名成fpc-i386-win32-dlltool-orig。
4 }

5 program fpc_i386_win32_dlltool;
6 {$mode objfpc}{$H+}
7 uses
8 Classes, SysUtils, Process;
9 var
10 i: integer;
11 s: ansistring;
12 AProcess: TProcess;
13 begin
14 s:=ParamStr(1);
15 For i:=2 to ParamCount() do
16 s:=s + ' ' + ParamStr(i);
17 WriteLn('wrapping: fpc-i386-win32-dlltool ', s);
18 AProcess:=TProcess.Create(nil);
19 AProcess.CommandLine := 'fpc-i386-win32-dlltool-orig '+ s;
20 AProcess.Options := AProcess.Options + [poWaitOnExit];
21 AProcess.Execute;
22 AProcess.Free;
23 end.
好在shell是强大的。所以这个问题可以很容易地解决。所以,最后的Makefile就成这样了-_-!。为了让这个Makefile见得了人,我重新改了一下,汗死...

Makefile

all: win32

.pas.exe:

fpc -o$@ -Twin32 $^

.pas.dll:

fpc -o$@ -Twin32 $^ || exit 0 # 链接成功后会有一个莫名其妙的错误信息(100%是bug!),汗..

win32:
app.exe win32lib.dll
win32lib.dll: win32lib.pas
app.exe: app.pas

clean:

rm -rf *.dll *.exe *.o *.s *.res *./$/$/$

.PHONY:
win32 clean all
.SUFFIXES: .pas .exe .dll

写这篇文章还有一个好处,至少让我用熟了code2html,同时也知道了在pascal方面pas2html和code2html都不怎么好用(看上面的结果就知道了,一部分经过我的再排版)。汗死...



 
原创粉丝点击