138
Free Pascal Programmers’ manual Programmers’ manual for Free Pascal, version 1.0.8 Document version 1.9 May 2003 Michaël Van Canneyt

Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Embed Size (px)

Citation preview

Page 1: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Free PascalProgrammers’ manual

Programmers’ manual for Free Pascal, version 1.0.8Document version 1.9

May 2003

Michaël Van Canneyt

Page 2: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Contents

0.1 About this document. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11

1 Compiler directives 12

1.1 Local directives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12

$A or $ALIGN : Align Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

$ASMMODE: Assembler mode (Intel 80x86 only). . . . . . . . . . . . . . . . . . . 12

$B or $BOOLEVAL: Complete boolean evaluation. . . . . . . . . . . . . . . . . . 13

$C or $ASSERTIONS: Assertion support. . . . . . . . . . . . . . . . . . . . . . . 13

$DEFINE : Define a symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

$ELSE : Switch conditional compilation. . . . . . . . . . . . . . . . . . . . . . . . 14

$ENDIF : End conditional compilation . . . . . . . . . . . . . . . . . . . . . . . . 14

$ERROR: Generate error message. . . . . . . . . . . . . . . . . . . . . . . . . . . 14

$F : Far or near functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

$FATAL : Generate fatal error message. . . . . . . . . . . . . . . . . . . . . . . . 15

$GOTO: SupportGoto andLabel . . . . . . . . . . . . . . . . . . . . . . . . . . 15

$H or $LONGSTRINGS: Use AnsiStrings. . . . . . . . . . . . . . . . . . . . . . . 16

$HINT : Generate hint message. . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

$HINTS : Emit hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16

$IF : Start conditional compilation . . . . . . . . . . . . . . . . . . . . . . . . . . 16

$IFDEF Name : Start conditional compilation. . . . . . . . . . . . . . . . . . . . 16

$IFNDEF : Start conditional compilation. . . . . . . . . . . . . . . . . . . . . . . 16

$IFOPT : Start conditional compilation. . . . . . . . . . . . . . . . . . . . . . . . 16

$INFO : Generate info message. . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

$INLINE : Allow inline code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

$I or $IOCHECKS: Input/Output checking. . . . . . . . . . . . . . . . . . . . . . 17

$I or $INCLUDE : Include file . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

$I or $INCLUDE : Include compiler info . . . . . . . . . . . . . . . . . . . . . . . 18

$I386_XXX : Specify assembler format (Intel 80x86 only). . . . . . . . . . . . . . 19

$L or $LINK : Link object file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

$LINKLIB : Link to a library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

$Mor $TYPEINFO : Generate type info. . . . . . . . . . . . . . . . . . . . . . . . 20

1

Page 3: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CONTENTS

$MACRO: Allow use of macros. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

$MAXFPUREGISTERS: Maximum number of FPU registers for variables (Intel80x86 only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21

$MESSAGE: Generate info message. . . . . . . . . . . . . . . . . . . . . . . . . . 21

$MMX: Intel MMX support (Intel 80x86 only). . . . . . . . . . . . . . . . . . . . . 21

$NOTE: Generate note message. . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

$NOTES: Emit notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22

$OUTPUT_FORMAT: Specify the output format. . . . . . . . . . . . . . . . . . . . 22

$P or $OPENSTRINGS: Use open strings. . . . . . . . . . . . . . . . . . . . . . . 22

$PACKENUM: Minimum enumeration type size. . . . . . . . . . . . . . . . . . . . 23

$PACKRECORDS: Alignment of record elements. . . . . . . . . . . . . . . . . . . 23

$Q $OVERFLOWCHECKS: Overflow checking. . . . . . . . . . . . . . . . . . . . . 24

$R or $RANGECHECKS: Range checking. . . . . . . . . . . . . . . . . . . . . . . 24

$SATURATION: Saturation operations (Intel 80x86 only). . . . . . . . . . . . . . 24

$SMARTLINK: Use smartlinking . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

$STATIC : Allow use ofStatic keyword.. . . . . . . . . . . . . . . . . . . . . . 25

$STOP: Generate fatal error message. . . . . . . . . . . . . . . . . . . . . . . . . 25

$T or $TYPEDADDRESS: Typed address operator (@). . . . . . . . . . . . . . . . 25

$UNDEF: Undefine a symbol. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

$V or $VARSTRINGCHECKS: Var-string checking. . . . . . . . . . . . . . . . . . 26

$WAIT : Wait for enter key press. . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

$WARNING: Generate warning message. . . . . . . . . . . . . . . . . . . . . . . . 26

$WARNINGS: Emit warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

$X or $EXTENDEDSYNTAX: Extended syntax. . . . . . . . . . . . . . . . . . . . 26

1.2 Global directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27

$APPTYPE: Specify type of application (Win32 and AmigaOS only). . . . . . . . 27

$D or $DEBUGINFO: Debugging symbols . . . . . . . . . . . . . . . . . . . . . . 27

$DESCRIPTION: Application description . . . . . . . . . . . . . . . . . . . . . . 27

$E : Emulation of coprocessor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Intel 80x86 version. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

Motorola 680x0 version . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

$G : Generate 80286 code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

$INCLUDEPATH: Specify include path.. . . . . . . . . . . . . . . . . . . . . . . . 28

$L or $LOCALSYMBOLS: Local symbol information. . . . . . . . . . . . . . . . . 28

$LIBRARYPATH: Specify library path.. . . . . . . . . . . . . . . . . . . . . . . . 29

$Mor $MEMORY: Memory sizes. . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

$MODE: Set compiler compatibility mode. . . . . . . . . . . . . . . . . . . . . . . 29

$N : Numeric processing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

$O : Overlay code generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

$OBJECTPATH: Specify object path.. . . . . . . . . . . . . . . . . . . . . . . . . 30

2

Page 4: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CONTENTS

$S : Stack checking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30

$UNITPATH : Specify unit path.. . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

$Wor $STACKFRAMES: Generate stackframes. . . . . . . . . . . . . . . . . . . . 31

$Y or $REFERENCEINFO: Insert Browser information . . . . . . . . . . . . . . . 31

2 Using conditionals, messages and macros 32

2.1 Conditionals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32

Predefined symbols. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36

2.2 Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36

2.3 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37

3 Using Assembly language 39

3.1 Intel 80x86 Inline assembler. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

Intel syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39

AT&T Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41

3.2 Motorola 680x0 Inline assembler. . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

3.3 Signaling changed registers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

4 Generated code 45

4.1 Units. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45

4.2 Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .46

5 Intel MMX support 47

5.1 What is it about? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .47

5.2 Saturation support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .48

5.3 Restrictions of MMX support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5.4 Supported MMX operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

5.5 Optimizing MMX support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

6 Code issues 50

6.1 Register Conventions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50

accumulator register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50

accumulator 64-bit register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

float result register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50

self register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50

frame pointer register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50

stack pointer register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51

scratch registers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51

Processor mapping of registers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Intel 80x86 version. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Motorola 680x0 version . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

6.2 Name mangling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52

3

Page 5: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CONTENTS

Mangled names for data blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Mangled names for code blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Modifying the mangled names. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

6.3 Calling mechanism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55

6.4 Nested procedure and functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

6.5 Constructor and Destructor calls. . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56

classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57

6.6 Entry and exit code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57

Intel 80x86 standard routine prologue / epilogue. . . . . . . . . . . . . . . . . . . . 57

Motorola 680x0 standard routine prologue / epilogue. . . . . . . . . . . . . . . . . 58

6.7 Parameter passing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

Parameter alignment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

6.8 Processor limitations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59

7 Linking issues 60

7.1 Using external code and variables. . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Declaring external functions or procedures. . . . . . . . . . . . . . . . . . . . . . . 60

Declaring external variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Declaring the calling convention modifier. . . . . . . . . . . . . . . . . . . . . . . 63

Declaring the external object code. . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Linking to an object file . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Linking to a library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

7.2 Making libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65

Exporting functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65

Exporting variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66

Compiling libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66

Unit searching strategy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67

7.3 Using smart linking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67

8 Memory issues 69

8.1 The memory model.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .69

8.2 Data formats. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70

integer types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70

char types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70

boolean types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70

enumeration types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70

floating point types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71

single . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71

double. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72

extended . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72

4

Page 6: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CONTENTS

comp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72

real . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72

pointer types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72

string types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73

ansistring types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73

shortstring types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

widestring types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

set types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73

array types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73

record types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74

object types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74

class types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74

file types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75

procedural types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76

8.3 Data alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76

Typed constants and variable alignment. . . . . . . . . . . . . . . . . . . . . . . . 76

Structured types alignment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

8.4 The heap. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77

Heap allocation strategy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

The HeapError variable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78

The heap grows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78

Debugging the heap. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79

Writing your own memory manager. . . . . . . . . . . . . . . . . . . . . . . . . . 79

8.5 UsingDOS memory under the Go32 extender. . . . . . . . . . . . . . . . . . . . . 82

9 Resource strings 84

9.1 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84

9.2 The resource string file. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84

9.3 Updating the string tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

9.4 GNU gettext. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87

9.5 Caveat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88

10 Optimizations 89

10.1 Non processor specific. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89

Constant folding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89

Constant merging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89

Short cut evaluation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89

Constant set inlining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89

Small sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90

Range checking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90

And instead of modulo. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90

5

Page 7: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CONTENTS

Shifts instead of multiply or divide. . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Automatic alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90

Smart linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90

Inline routines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90

Stack frame omission. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90

Register variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91

10.2 Processor specific. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91

Intel 80x86 specific. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91

Motorola 680x0 specific . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

10.3 Optimization switches. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93

10.4 Tips to get faster code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .94

10.5 Tips to get smaller code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .94

11 Programming shared libraries 95

11.1 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

11.2 Creating a library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

11.3 Using a library in a pascal program. . . . . . . . . . . . . . . . . . . . . . . . . . . 96

11.4 Using a pascal library from a C program. . . . . . . . . . . . . . . . . . . . . . . . 98

12 Using Windows resources 100

12.1 The resource directive$R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100

12.2 Creating resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100

12.3 Using string tables.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101

12.4 Inserting version information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101

12.5 Inserting an application icon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102

12.6 Using a pascal preprocessor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102

A Anatomy of a unit file 104

A.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104

A.2 reading ppufiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104

A.3 The Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .105

A.4 The sections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106

A.5 Creating ppufiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107

B Compiler and RTL source tree structure 110

B.1 The compiler source tree. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110

B.2 The RTL source tree. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110

C Compiler limits 112

D Compiler modes 113

D.1 FPC mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113

6

Page 8: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CONTENTS

D.2 TP mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113

D.3 Delphi mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114

D.4 GPC mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114

D.5 OBJFPC mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114

E Using fpcmake 116

E.1 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .116

E.2 Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .116

E.3 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .117

E.4 Format of the configuration file. . . . . . . . . . . . . . . . . . . . . . . . . . . . .118

clean. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .118

compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .118

Default . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119

Dist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119

Install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120

Package. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120

Prerules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120

Requires. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120

Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121

Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121

E.5 Programs needed to use the generated makefile. . . . . . . . . . . . . . . . . . . .122

E.6 Variables that affect the generated makefile. . . . . . . . . . . . . . . . . . . . . .122

Directory variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123

Compiler command-line variables. . . . . . . . . . . . . . . . . . . . . . . . . . .123

E.7 Variables set byfpcmake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123

Directory variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124

Target variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125

Compiler command-line variables. . . . . . . . . . . . . . . . . . . . . . . . . . .126

Program names. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .126

File extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127

Target files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127

E.8 Rules and targets created byfpcmake . . . . . . . . . . . . . . . . . . . . . . . . .127

Pattern rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127

Build rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128

Cleaning rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128

archiving rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128

Installation rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128

Informative rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129

F Compiling the compiler 130

F.1 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .130

7

Page 9: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CONTENTS

F.2 Before starting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .130

F.3 Compiling usingmake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .131

F.4 Compiling by hand. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132

Compiling the RTL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132

Compiling the compiler. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133

G Compiler defines during compilation 135

H Operating system specific behavior 137

8

Page 10: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

List of Tables

1.1 Formats generated by the x86 compiler. . . . . . . . . . . . . . . . . . . . . . . . . 23

2.1 Predefined macros. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38

6.1 Intel 80x86 Register table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

6.2 Motorola 680x0 Register table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

6.3 Calling mechanisms in Free Pascal. . . . . . . . . . . . . . . . . . . . . . . . . . . 56

6.4 Stack frame when calling a nested procedure (32-bit processors). . . . . . . . . . . 56

6.5 Stack frame when calling a procedure (32-bit model). . . . . . . . . . . . . . . . . 58

6.6 Maximum limits for processors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

8.1 Enumeration storage fortp mode . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

8.2 Processor mapping of real type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

8.3 AnsiString memory structure (32-bit model). . . . . . . . . . . . . . . . . . . . . . 73

8.4 Object memory layout (32-bit model). . . . . . . . . . . . . . . . . . . . . . . . . 74

8.5 Object Virtual Method Table memory layout (32-bit model). . . . . . . . . . . . . . 74

8.6 Class memory layout (32-bit model). . . . . . . . . . . . . . . . . . . . . . . . . . 75

8.7 Class Virtual Method Table memory layout (32-bit model). . . . . . . . . . . . . . 75

8.8 Data alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77

8.9 Heap error result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78

8.10 ReturnNilIfGrowHeapFails value. . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

11.1 Shared library support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

A.1 PPU Header. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .105

A.2 PPU CPU Field values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .105

A.3 PPU Header Flag values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106

A.4 chunk data format. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106

A.5 Possible PPU Entry types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107

F.1 Possible defines when compiling FPC. . . . . . . . . . . . . . . . . . . . . . . . .134

G.1 Possible defines when compiling using FPC. . . . . . . . . . . . . . . . . . . . . .135

9

Page 11: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

LIST OF TABLES

G.2 Possible CPU defines when compiling using FPC. . . . . . . . . . . . . . . . . . .136

G.3 Possible defines when compiling using target OS. . . . . . . . . . . . . . . . . . .136

H.1 Operating system specific behavior. . . . . . . . . . . . . . . . . . . . . . . . . . .137

10

Page 12: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

LIST OF TABLES

0.1 About this document

This is the programmer’s manual for Free Pascal.

It describes some of the peculiarities of the Free Pascal compiler, and provides a glimpse of howthe compiler generates its code, and how you can change the generated code. It will not, however,provide a detailed account of the inner workings of the compiler, nor will it describe how to use thecompiler (described in theUsers guide). It also will not describe the inner workings of the Run-TimeLibrary (RTL). The best way to learn about the way the RTL is implemented is from the sourcesthemselves.

The things described here are useful when things need to be done that require greater flexibility thanthe standard Pascal language constructs (described in theReference guide).

Since the compiler is continuously under development, this document may get out of date. Whereverpossible, the information in this manual will be updated. If you find something which isn’t correct,or you think something is missing, feel free to contact me1.

[email protected]

11

Page 13: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 1

Compiler directives

Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascaldirectives, although some are supported for compatibility. There is a distinction between local andglobal directives; local directives take effect from the moment they are encountered, global directiveshave an effect on all of the compiled code.

Many switches have a long form also. If they do, then the name of the long form is given also. Forlong switches, the + or - character to switch the option on or off, may be replaced byONor OFFkeywords.

Thus{$I+} is equivalent to{$IOCHECKS ON} or {$IOCHECKS +} and{$C-} is equivalentto {$ASSERTIONS OFF} or {$ASSERTIONS -}

The long forms of the switches are the same as their Delphi counterparts.

1.1 Local directives

Local directives can occur more than once in a unit or program, If they have a command-line counter-part, the command-line argument is restored as the default for each compiled file. The local directivesinfluence the compiler’s behaviour from the moment they’re encountered until the moment anotherswitch annihilates their behaviour, or the end of the current unit or program is reached.

$A or $ALIGN : Align DataThis switch is recognized for Turbo Pascal Compatibility, but is not yet implemented. The alignmentof data will be different in any case.

$ASMMODE: Assembler mode (Intel 80x86 only)The {$ASMMODE XXX}directive informs the compiler what kind of assembler it can expect in anasm block. TheXXXshould be replaced by one of the following:

att Indicates thatasm blocks contain AT&T syntax assembler.

intel Indicates thatasm blocks contain Intel syntax assembler.

direct Tells the compiler that asm blocks should be copied directly to the assembler file.

12

Page 14: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

These switches are local, and retain their value to the end of the unit that is compiled, unless they arereplaced by another directive of the same type. The command-line switch that corresponds to thisswitch is-R .

The default assembler reader is the AT&T reader.

$B or $BOOLEVAL: Complete boolean evaluationThis switch is understood by the Free Pascal compiler, but is ignored. The compiler always usesshortcut evaluation, i.e. the evaluation of a boolean expression is stopped once the result of the totalexression is known with certainty.

So, in the following example, the functionBofu , which has a boolean result, will never get called.

If False and Bofu then...

This has as a consequence that any additional actions that are done byBofu are not executed.

$C or $ASSERTIONS: Assertion supportThe {$ASSERTIONS} switch determines if assert statements are compiled into the binary or not.If the switch is on, the statement

Assert(BooleanExpression,AssertMessage);

Will be compiled in the binary. If teBooleanExpression evaluates toFalse , the RTL willcheck if theAssertErrorProc is set. If it is set, it will be called with as parameters theAssertMessage message, the name of the file, the LineNumber and the address. If it is notset, a runtime error 227 is generated.

TheAssertErrorProc is defined as

TypeTAssertErrorProc=procedure(const msg,fname:string;lineno,erroraddr:longint);

VarAssertErrorProc = TAssertErrorProc;

This can be used mainly for debugging purposes. Thesystem unit sets theAssertErrorProcto a handler that displays a message onstderr and simply exits. Thesysutils unit catches therun-time error 227 and raises anEAssertionFailed exception.

$DEFINE : Define a symbolThe directive

{$DEFINE name}

defines the symbolname. This symbol remains defined until the end of the current module (i.e. unitor program), or until a$UNDEF namedirective is encountered.

If name is already defined, this has no effect.Nameis case insensitive.

The symbols that are defined in a unit, are not saved in the unit file, so they are also not exportedfrom a unit.

13

Page 15: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

$ELSE : Switch conditional compilationThe{$ELSE} switches between compiling and ignoring the source text delimited by the preceding{$IFxxx} and following {$ENDIF} . Any text after theELSE keyword but before the brace isignored:

{$ELSE some ignored text}

is the same as

{$ELSE}

This is useful for indication what switch is meant.

$ENDIF : End conditional compilationThe{$ENDIF} directive ends the conditional compilation initiated by the last{$IFxxx} directive.Any text after theENDIF keyword but before the closing brace is ignored:

{$ENDIF some ignored text}

is the same as

{$ENDIF}

This is useful for indication what switch is meant to be ended.

$ERROR: Generate error messageThe following code

{$ERROR This code is erroneous !}

will display an error message when the compiler encounters it, and increase the error count of thecompiler. The compiler will continue to compile, but no code will be emitted.

$F : Far or near functionsThis directive is recognized for compatibility with Turbo Pascal. Under the 32-bit and 64-bit pro-gramming models, the concept of near and far calls have no meaning, hence the directive is ignored.A warning is printed to the screen, as a reminder.

As an example, the following piece of code:

{$F+}

Procedure TestProc;

beginWriteln (’Hello From TestProc’);

end;

begintestProc

end.

14

Page 16: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

Generates the following compiler output:

malpertuus: >pp -vw testfCompiler: ppc386Units are searched in: /home/michael;/usr/bin/;/usr/lib/ppc/0.9.1/linuxunitsTarget OS: LinuxCompiling testf.pptestf.pp(1) Warning: illegal compiler switch7739 kB freeCalling assembler...Assembled...Calling linker...12 lines compiled,

1.00000000000000E+0000

One can see that the verbosity level was set to display warnings.

When declaring a function asFar (this has the same effect as setting it between{$F+} ...{$F-}directives), the compiler also generates a warning:

testf.pp(3) Warning: FAR ignored

The same story is true for procedures declared asNear . The warning displayed in that case is:

testf.pp(3) Warning: NEAR ignored

$FATAL : Generate fatal error messageThe following code

{$FATAL This code is erroneous !}

will display an error message when the compiler encounters it, and the compiler will immediatly stopthe compilation process.

This is mainly useful inc conjunction wih{$IFDEF} or {$IFOPT} statements.

$GOTO: Support Goto and Label

If {$GOTO ON}is specified, the compiler will supportGoto statements andLabel declarations.By default,$GOTO OFFis assumed. This directive corresponds to the-Sg command-line option.

As an example, the following code can be compiled:

{$GOTO ON}

label Theend;

beginIf ParamCount=0 then

GoTo TheEnd;Writeln (’You specified command-line options’);

TheEnd:end.

Remark: When compiling assembler code using the inline assembler readers, any labels used in the assemblercode must be declared, and the{$GOTO ON}directive should be used.

15

Page 17: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

$H or $LONGSTRINGS: Use AnsiStringsIf {$LONGSTRINGS ON}is specified, the keywordString (no length specifier) will be treatedasAnsiString , and the compiler will treat the corresponding variable as an ansistring, and willgenerate corresponding code.

By default, the use of ansistrings is off, corresponding to{$H-} . The system unit is compiledwithout ansistrings, all its functions accept shortstring arguments. The same is true for all RTL units,except thesysutils unit, which is compiled with ansistrings.

$HINT : Generate hint messageIf the generation of hints is turned on, through the-vh command-line option or the{$HINTS ON}directive, then

{$Hint This code should be optimized }

will display a hint message when the compiler encounters it.

By default, no hints are generated.

$HINTS : Emit hints{$HINTS ON} switches the generation of hints on.{$HINTS OFF} switches the generation ofhints off. Contrary to the command-line option-vh this is a local switch, this is useful for checkingparts of the code.

$IF : Start conditional compilationThe directive{$IF expr} will continue the compilation if the boolean expressionexpr evaluatesto true . If the compilation evaluates to false, then the source is skipped to the first{$ELSE} or{$ENDIF} directive.

The compiler must be able to evaluate the expression at parse time. This means that variables orconstants that are defined in the source cannot be used. Macros and symbols may be used, however.

More information on this can be found in the section about conditionals.

$IFDEF Name : Start conditional compilationIf the symbolNameis not defined then the{$IFDEF name} will skip the compilation of the textthat follows it to the first{$ELSE} or {$ENDIF} directive. If Nameis defined, then compilationcontinues as if the directive wasn’t there.

$IFNDEF : Start conditional compilationIf the symbolName is defined then the{$IFNDEF name} will skip the compilation of the textthat follows it to the first{$ELSE} or {$ENDIF} directive. If it is not defined, then compilationcontinues as if the directive wasn’t there.

$IFOPT : Start conditional compilationThe{$IFOPT switch} will compile the text that follows it if the switchswitch is currently inthe specified state. If it isn’t in the specified state, then compilation continues after the corresponding

16

Page 18: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

{$ELSE} or {$ENDIF} directive.

As an example:

{$IFOPT M+}Writeln (’Compiled with type information’);

{$ENDIF}

Will compile the writeln statement if generation of type information is on.

Remark: The {$IFOPT} directive accepts only short options, i.e.{$IFOPT TYPEINFO} will not be ac-cepted.

$INFO : Generate info messageIf the generation of info is turned on, through the-vi command-line option, then

{$INFO This was coded on a rainy day by Bugs Bunny}

will display an info message when the compiler encounters it.

This is useful in conjunction with the{$IFDEF} directive, to show information about which part ofthe code is being compiled.

$INLINE : Allow inline code.The {$INLINE ON} directive tells the compiler that theInline procedure modifier should beallowed. Procedures that are declared inline are copied to the places where they are called. This hasthe effect that there is no actual procedure call, the code of the procedure is just copied to where theprocedure is needed, this results in faster execution speed if the function or procedure is used a lot.

By default, Inline procedures are not allowed. This directive must be specified to use inlinedcode. The directive is equivalent to the command-line switch-Si . For more information on inlineroutines, consult theReference guide.

$I or $IOCHECKS: Input/Output checkingThe{$I-} or {$IOCHECKS OFF} directive tells the compiler not to generate input/output check-ing code in the program. By default, the compiler does not generate this code, it must be switchedon using the-Ci command-line switch.

When compiling using the-Ci compiler switch, the Free Pascal compiler inserts input/output check-ing code after every input/output call in the code. If an error occurred during input or output, then arun-time error will be generated. Use this switch to avoid this behaviour.

To check if something went wrong, theIOResult function can be used to see if everything wentwithout problems.

Conversely,{$I+} will turn error-checking back on, until another directive is encountered whichturns it off again.

The most common use for this switch is to check if the opening of a file went without problems, asin the following piece of code:

assign (f,’file.txt’);{$I-}rewrite (f);

17

Page 19: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

{$I+}if IOResult<>0 then

beginWriteln (’Error opening file: "file.txt"’);exitend;

See theIOResult function explanation inReference guidefor a detailed description of the possibleerrors that can occur when using input/output checking.

$I or $INCLUDE : Include fileThe {$I filename} or {$INCLUDE filename} directive tells the compiler to read furtherstatements from the filefilename . The statements read there will be inserted as if they occurredin the current file.

The compiler will append the.pp extension to the file if no extension is given. Do not put thefilename between quotes, as they will be regarded as part of the file’s name.

Include files can be nested, but not infinitely deep. The number of files is restricted to the number offile descriptors available to the Free Pascal compiler.

Contrary to Turbo Pascal, include files can cross blocks. I.e. a block can start in one file (with aBegin keyword) and can end in another (with aEnd keyword). The smallest entity in an includefile must be a token, i.e. an identifier, keyword or operator.

The compiler will look for the file to include in the following places:

1. It will look in the path specified in the include file name.

2. It will look in the directory where the current source file is.

3. it will look in all directories specified in the include file search path.

Directories can be added to the include file search path with the-I command-line option.

$I or $INCLUDE : Include compiler infoIn this form:

{$INCLUDE %xxx%}

wherexxx is one of the following:

DATE Inserts the current date.

FPCTARGET Inserts the target CPU name. (deprecated, useFPCTARGETCPU)

FPCTARGETCPU Inserts the target CPU name.

FPCTARGETOS Inserts the target OS name.

FPCVERSION Current compiler version number.

FILE Filename in which the directive is found.

LINE Linenumer on which the directive is found.

18

Page 20: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

TIME Current time.

If xxx is none of the above, then it is assumed to be the name of an environment variable. Its valuewill be fetched. As a reult, this will generate a macro with the value of these things, as if it were astring.

For example, the following program

Program InfoDemo;

Const User = {$I %USER%};

beginWrite (’This program was compiled at ’,{$I %TIME%});Writeln (’ on ’,{$I %DATE%});Writeln (’By ’,User);Writeln (’Compiler version: ’,{$I %FPCVERSION%});Writeln (’Target CPU: ’,{$I %FPCTARGET%});

end.

Creates the following output:

This program was compiled at 17:40:18 on 1998/09/09By michaelCompiler version: 0.99.7Target CPU: i386

$I386_XXX : Specify assembler format (Intel 80x86 only)This switch selects the assembler reader.{$I386_XXX} has the same effect as{$ASMMODEXXX}, section1.1, page12

This switch is deprecated, the{$ASMMODE XXX}directive should be used instead.

$L or $LINK : Link object fileThe{$L filename} or {$LINK filename} directive tells the compiler that the filefilenameshould be linked to the program. This cannot be used for libraries, see section section1.1, page20for that.

The compiler will look for this file in the following way:

1. It will look in the path specified in the object file name.

2. It will look in the directory where the current source file is.

3. it will look in all directories specified in the object file search path.

Directories can be added to the object file search path with the-Fo option.

On LINUX systems and on operating systems with case-sensitive filesystems (such asUNIX systems),the name is case sensitive, and must be typed exactly as it appears on your system.

Remark: Take care that the object file you’re linking is in a format the linker understands. Which format thisis, depends on the platform you’re on. Typingld or ld -help on the command line gives a list offormatsld knows about.

19

Page 21: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

Other files and options can be passed to the linker using the-k command-line option. More thanone of these options can be used, and they will be passed to the linker, in the order that they werespecified on the command line, just before the names of the object files that must be linked.

$LINKLIB : Link to a libraryThe{$LINKLIB name} will link to a library name. This has the effect of passing-lname to thelinker.

As an example, consider the following unit:

unit getlen;

interface{$LINKLIB c}

function strlen (P : pchar) : longint;cdecl;

implementation

function strlen (P : pchar) : longint;cdecl;external;

end.

If one would issue the command

ppc386 foo.pp

where foo.pp has the above unit in itsuses clause, then the compiler would link the program to thec library, by passing the linker the-lc option.

The same effect could be obtained by removing the linklib directive in the above unit, and specify-k-lc on the command-line:

ppc386 -k-lc foo.pp

$Mor $TYPEINFO : Generate type infoFor classes that are compiled in the{$M+} or {$TYPEINFO ON} state, the compiler will generateRun-Time Type Information (RTTI). All descendent objects of an object that was compiled in the{$M+} state will get RTTI information too, as well as any published classes. By default, no Run-Time Type Information is generated. TheTPersistent object that is present in the FCL (FreeComponent Library) is generated in the{$M+} state. The generation of RTTI allows programmersto stream objects, and to access published properties of objects, without knowing the actual class ofthe object.

The run-time type information is accessible through theTypInfo unit, which is part of the FreePascal Run-Time Library.

Remark: The streaming system implemented by Free Pascal requires that all streamable components be des-cendent fromTPersistent .

$MACRO: Allow use of macros.In the {$MACRO ON}state, the compiler allows to use C-style (although not as elaborate) macros.Macros provide a means for simple text substitution. More information on using macros can be found

20

Page 22: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

in the section2.3, page37section. This directive is equivalent to the command-line switch-Sm.

By default, macros are not allowed.

$MAXFPUREGISTERS: Maximum number of FPU registers for variables(Intel 80x86 only)The {$MAXFPUREGISTERS XXX}directive tells the compiler how much floating point variablescan be kept in the floating point processor registers. This switch is ignored unless the-Or (useregister variables) optimization is used.

This is quite tricky because the Intel FPU stack is limited to 8 entries. The compiler uses a heuristicalgorithm to determine how much variables should be put onto the stack: in leaf procedures it islimited to 3 and in non leaf procedures to 1. But in case of a deep call tree or, even worse, a recursiveprocedure this can still lead to a FPU stack overflow, so the user can tell the compiler how much(floating point) variables should be kept in registers.

The directive accepts the following arguments:

N whereN is the maximum number of FPU registers to use. Currently this can be in the range 0 to7.

Normal restores the heuristic and standard behavior.

Default restores the heuristic and standard behaviour.

Remark: This directive is valid until the end of the current procedure.

$MESSAGE: Generate info messageIf the generation of info is turned on, through the-vi command-line option, then

{$MESSAGE This was coded on a rainy day by Bugs Bunny }

will display an info message when the compiler encounters it. The effect is the same as the{$INFO}directive.

$MMX: Intel MMX support (Intel 80x86 only)Free Pascal supports optimization for theMMX Intel processor (see also chapter5).

This optimizes certain code parts for theMMX Intel processor, thus greatly improving speed. Thespeed is noticed mostly when moving large amounts of data. Things that change are

• Data with a size that is a multiple of 8 bytes is moved using themovq assembler instruction,which moves 8 bytes at a time

Remark: MMX support is NOT emulated on non-MMX systems, i.e. if the processor doesn’t have the MMXextensions, the MMX optimizations cannot be used.

WhenMMX support is on, it is not allowed to do floating point arithmetic. It is allowed to movefloating point data, but no arithmetic can be done. If floating point math must be done anyway, firstMMX support must be switched off and the FPU must be cleared using theemmsfunction of thecpu unit.

The following example will make this more clear:

21

Page 23: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

Program MMXDemo;

uses mmx;

vard1 : double;a : array[0..10000] of double;i : longint;

begind1:=1.0;

{$mmx+}{ floating point data is used, but we do _no_ arithmetic }for i:=0 to 10000 do

a[i]:=d2; { this is done with 64 bit moves }{$mmx-}

emms; { clear fpu }{ now we can do floating point arithmetic }...

end.

See, however, the chapter on MMX (5) for more information on this topic.

$NOTE: Generate note messageIf the generation of notes is turned on, through the-vn command-line option or the{$NOTES ON}directive, then

{$NOTE Ask Santa Claus to look at this code}

will display a note message when the compiler encounters it.

$NOTES: Emit notes{$NOTES ON}switches the generation of notes on.{$NOTES OFF} switches the generation ofnotes off. Contrary to the command-line option-vn this is a local switch, this is useful for checkingparts of the code.

By default,{$NOTES} is off.

$OUTPUT_FORMAT: Specify the output format{$OUTPUT_FORMAT format} has the same functionality as the-A command-line option: it tellsthe compiler what kind of object file must be generated. You can specify this switch onlybeforetheProgram or Unit clause in your source file. The different kinds of formats are shown in table(1.1).

The default output format depends on the platform the compiler was compiled on.

$P or $OPENSTRINGS: Use open stringsIf this switch is on, all function or procedure parameters of type string are considered to be openstring parameters; this parameter only has effect for short strings, not for ansistrings.

22

Page 24: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

Table 1.1: Formats generated by the x86 compiler

Switch value Generated formatAS AT&T assembler file.AS_AOUT Go32v1 assembler file.ASW AT&T Win32 assembler file.COFF Go32v2 COFF object file.MASM Masm assembler file.NASM Nasm assembler file.NASMCOFF Nasm assembler file (COFF format).NASMELF Nasm assembler file (ELF format).PECOFF PECOFF object file (Win32).TASM Tasm assembler file.

When using openstrings, the declared type of the string can be different from the type of string that isactually passed, even for strings that are passed by reference. The declared size of the string passedcan be examined with theHigh(P) call.

Default the use of openstrings is off.

$PACKENUM: Minimum enumeration type sizeThis directive tells the compiler the minimum number of bytes it should use when storing enumeratedtypes. It is of the following form:

{$PACKENUM xxx}{$MINENUMSIZE xxx}

Where the form with$MINENUMSIZEis for Delphi compatibility.xxx can be one of1,2 or 4, orNORMALor DEFAULT.

As an alternative form one can use{$Z1} , {$Z2} {$Z4} . Contrary to Delphi, the default is({$Z4} ).

So the following code

{$PACKENUM 1}Type

Days = (monday, tuesday, wednesday, thursday, friday,saturday, sunday);

will use 1 byte to store a variable of typeDays , whereas it nomally would use 4 bytes. The abovecode is equivalent to

{$Z1}Type

Days = (monday, tuesday, wednesday, thursday, friday,saturday, sunday);

$PACKRECORDS: Alignment of record elementsThis directive controls the byte alignment of the elements in a record, object or class type definition.

It is of the following form:

23

Page 25: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

{$PACKRECORDS n}

Wheren is one of 1, 2, 4, 16,C, NORMALor DEFAULT. This means that the elements of a recordthat have size greater thann will be aligned onn byte boundaries. Elements with size less than orequal ton will be aligned to a natural boundary, i.e. to a power of two that is equal to or larger thanthe element’s size. The typeC is used to specify alignment as by the GNU CC compiler. It should beused only when making import units for C routines.

The default alignment (which can be selected withDEFAULT) is 2, contrary to Turbo Pascal, whereit is 1.

More information on this and an example program can be found in the reference guide, in the sectionabout record types.

$Q $OVERFLOWCHECKS: Overflow checkingThe {$Q+} or {$OVERFLOWCHECKS ON}directive turns on integer overflow checking. Thismeans that the compiler inserts code to check for overflow when doing computations with integers.When an overflow occurs, the run-time library will print a messageOverflow at xxx , and exitthe program with exit code 215.

Remark: Overflow checking behaviour is not the same as in Turbo Pascal since all arithmetic operations aredone via 32-bit or 64-bit values. Furthermore, theInc() andDec standard system proceduresarechecked for overflow in Free Pascal, while in Turbo Pascal they are not.

Using the{$Q-} switch switches off the overflow checking code generation.

The generation of overflow checking code can also be controlled using the-Co command line com-piler option (seeUsers guide).

$R or $RANGECHECKS: Range checkingBy default, the compiler doesn’t generate code to check the ranges of array indices, enumerationtypes, subrange types, etc. Specifying the{$R+} switch tells the computer to generate code tocheck these indices. If, at run-time, an index or enumeration type is specified that is out of thedeclared range of the compiler, then a run-time error is generated, and the program exits with exitcode 201. This can happen when doing a typecast (implicit or explicit) on an enumeration type orsubrange type.

The {$RANGECHECKS OFF}switch tells the compiler not to generate range checking code. Thismay result in faulty program behaviour, but no run-time errors will be generated.

Remark: The standard functionsval andRead will also check ranges when the call is compiled in{$R+}mode.

$SATURATION: Saturation operations (Intel 80x86 only)This works only on the intel compiler, and MMX support must be on ({$MMX +}) for this to haveany effect. See the section on saturation support (section5.2, page48) for more information on theeffect of this directive.

$SMARTLINK: Use smartlinkingA unit that is compiled in the{$SMARTLINK ON} state will be compiled in such a way that it canbe used for smartlinking. This means that the unit is chopped in logical pieces: each procedure is putin it’s own object file, and all object files are put together in a big archive. When using such a unit,

24

Page 26: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

only the pieces of code that you really need or call, will be linked in your program, thus reducing thesize of your executable substantially.

Beware: using smartlinked units slows down the compilation process, because a separate object filemust be created for each procedure. If you have units with many functions and procedures, this canbe a time consuming process, even more so if you use an external assembler (the assembler is calledto assemble each procedure or function code block separately).

The smartlinking directive should be specifiedbeforethe unit declaration part:

{$SMARTLINK ON}

Unit MyUnit;

Interface...

This directive is equivalent to the-Cx command-line switch.

$STATIC : Allow use of Static keyword.If you specify the{$STATIC ON} directive, thenStatic methods are allowed for objects.Staticobjects methods do not require aSelf variable. They are equivalent toClass methods for classes.By default,Static methods are not allowed. Class methods are always allowed.

By default, the address operator returns an untyped pointer.

This directive is equivalent to the-St command-line option.

$STOP: Generate fatal error messageThe following code

{$STOP This code is erroneous !}

will display an error message when the compiler encounters it. The compiler will immediatly stopthe compilation process.

It has the same effect as the{$FATAL} directive.

$T or $TYPEDADDRESS: Typed address operator (@)In the{$T+} or {$TYPEDADDRESS ON}state the @ operator, when applied to a variable, returnsa result of typeT , if the type of the variable isT. In the{$T-} state, the result is always an untypedpointer, which is assignment compatible with all other pointer types.

$UNDEF: Undefine a symbolThe directive

{$UNDEF name}

un-defines the symbolname if it was previously defined.Nameis case insensitive.

25

Page 27: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

$V or $VARSTRINGCHECKS: Var-string checkingWhen in the+ or ONstate, the compiler checks that strings passed as parameters are of the same,identical, string type as the declared parameters of the procedure.

$WAIT : Wait for enter key pressIf the compiler encounters a

{$WAIT}

directive, it will resume compiling only after the user has pressed the enter key. If the generation ofinfo messages is turned on, then the compiler will display the following message:

Press <return> to continue

before waiting for a keypress.

Remark: This may interfere with automatic compilation processes. It should be used for debugging purposesonly.

$WARNING: Generate warning messageIf the generation of warnings is turned on, through the-vw command-line option or the{$WARNINGSON} directive, then

{$WARNING This is dubious code}

will display a warning message when the compiler encounters it.

$WARNINGS: Emit warnings{$WARNINGS ON}switches the generation of warnings on.{$WARNINGS OFF}switches thegeneration of warnings off. Contrary to the command-line option-vw this is a local switch, this isuseful for checking parts of your code.

By default, no warnings are emitted.

$X or $EXTENDEDSYNTAX: Extended syntaxExtended syntax allows you to drop the result of a function. This means that you can use a functioncall as if it were a procedure. Standard this feature is on. You can switch it off using the{$X-} or{$EXTENDEDSYNTAX OFF}directive.

The following, for instance, will not compile:

function Func (var Arg : sometype) : longint;begin... { declaration of Func }end;

...

{$X-}Func (A);

26

Page 28: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

The reason this construct is supported is that you may wish to call a function for certain side-effectsit has, but you don’t need the function result. In this case you don’t need to assign the function result,saving you an extra variable.

The command-line compiler switch-Sa1 has the same effect as the{$X+} directive.

By default, extended syntax is assumed.

1.2 Global directives

Global directives affect the whole of the compilation process. That is why they also have a command-line counterpart. The command-line counterpart is given for each of the directives.

$APPTYPE: Specify type of application (Win32 and AmigaOS only)The{$APPTYPE XXX} accepts one argument that can have two possible values:GUI orCONSOLE.It is used to tell the WINDOWS Operating system if an application is a console application or a graph-ical application. By default, a program compiled by Free Pascal is a console application. Running itwill display a console window. Specifying the{$APPTYPE GUI} directive will mark the applica-tion as a graphical application; no console window will be opened when the application is run. If runfrom the command-line, the command prompt will be returned immediatly after the application wasstarted.

Care should be taken when compilingGUI applications; theInput andOutput files are not avail-able in a GUI application, and attempting to read from or write to them will result in a run-timeerror.

It is possible to determine the application type of a WINDOWS or AMIGA application at runtime. TheIsConsole constant, declared in the Win32 and Amiga system units as

ConstIsConsole : Boolean

containsTrue if the application is a console application,False if the application is a GUI applic-ation.

$D or $DEBUGINFO: Debugging symbolsWhen this switch is on, the compiler inserts GNU debugging information in the executable. Theeffect of this switch is the same as the command-line switch-g .

By default, insertion of debugging information is off.

$DESCRIPTION : Application descriptionThis switch is recognised for compatibility only, but is ignored completely by the compiler. At a laterstage, this switch may be activated.

$E : Emulation of coprocessorThis directive controls the emulation of the coprocessor. There is no command-line counterpart forthis directive.

27

Page 29: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

Intel 80x86 version

When this switch is enabled, all floating point instructions which are not supported by standardcoprocessor emulators will give out a warning.

The compiler itself doesn’t do the emulation of the coprocessor.

To use coprocessor emulation underDOS go32v2 you must use the emu387 unit, which containscorrect initialization code for the emulator.

UnderLINUX and mostUNIX ’es, the kernel takes care of the coprocessor support.

Motorola 680x0 version

When the switch is on, no floating point opcodes are emitted by the code generator. Instead, internalrun-time library routines are called to do the necessary calculations. In this case all real types aremapped to the single IEEE floating point type.

Remark: By default, emulation is on for non-unix targets. For unix targets, floating point emulation (if re-quired) is handled by the operating system, and by default it is off.

$G : Generate 80286 codeThis option is recognised for Turbo Pascal compatibility, but is ignored, since the compiler worksonly on 32-bit and 64-bit processors.

$INCLUDEPATH: Specify include path.This option serves to specify the include path, where the compiler looks for include files.{$INCLUDEPATHXXX} will add XXXto the include path.XXXcan contain one or more paths, separated by semi-colonsor colons.

For example:

{$INCLUDEPATH ../inc;../i386}

{$I strings.inc}

will add the directories../inc and../i386 to the include path of the compiler. The compiler will lookfor the filestrings.inc in both these directories, and will include the first found file. This directive isequivalent to the-Fi command-line switch.

Caution is in order when using this directive: If you distribute files, the places of the files may not bethe same as on your machine; moreover, the directory structure may be different. In general it wouldbe fair to say that you should avoid usingabsolutepaths, instead userelativepaths, as in the exampleabove. Only use this directive if you are certain of the places where the files reside. If you are notsure, it is better practice to use makefiles and makefile variables.

$L or $LOCALSYMBOLS: Local symbol informationThis switch (not to be confused with the{$L file} file linking directive) is recognised for TurboPascal compatibility, but is ignored. Generation of symbol information is controlled by the$Dswitch.

28

Page 30: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

$LIBRARYPATH: Specify library path.This option serves to specify the library path, where the linker looks for static or dynamic libraries.{$LIBRARYPATH XXX} will add XXX to the library path.XXXcan contain one or more paths,separated by semi-colons or colons.

For example:

{$LIBRARYPATH /usr/X11/lib;/usr/local/lib}

{$LINKLIB X11}

will add the directories/usr/X11/lib and /usr/local/lib to the linker library path. The linker willlook for the librarylibX11.so in both these directories, and use the first found file. This directive isequivalent to the-Fl command-line switch.

Caution is in order when using this directive: If you distribute files, the places of the libraries maynot be the same as on your machine; moreover, the directory structure may be different. In general itwould be fair to say that you should avoid using this directive. If you are not sure, it is better practiceto use makefiles and makefile variables.

$Mor $MEMORY: Memory sizesThis switch can be used to set the heap and stacksize. It’s format is as follows:

{$M StackSize,HeapSize}

whereStackSize and HeapSize should be two integer values, greater than 1024. The firstnumber sets the size of the stack, and the second the size of the heap. (Stack setting is ignored underLINUX , NETBSD and FREEBSD). The two numbers can be set on the command line using the-Chand-Cs switches.

$MODE: Set compiler compatibility modeThe {$MODE} sets the compatibility mode of the compiler. This is equivalent to setting one of thecommand-line options-So , -Sd , -Sp or -S2 . it has the following arguments:

Default Default mode. This reverts back to the mode that was set on the command-line.

Delphi Delphi compatibility mode. All object-pascal extensions are enabled. This is the same as thecommand-line option-Sd .

TP Turbo pascal compatibility mode. Object pascal extensions are disabled, except ansistrings,which remain valid. This is the same as the command-line option-So .

FPC FPC mode. This is the default, if no command-line switch is supplied.

OBJFPC Object pascal mode. This is the same as the-S2 command-line option.

GPC GNU pascal mode. This is the same as the-Sp command-line option.

For an exact description of each of these modes, see appendixD, on page113.

$N : Numeric processingThis switch is recognised for Turbo Pascal compatibility, but is otherwise ignored, since the compileralways uses the coprocessor for floating point mathematics.

29

Page 31: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

$O : Overlay code generationThis switch is recognised for Turbo Pascal compatibility, but is otherwise ignored.

$OBJECTPATH: Specify object path.This option serves to specify the object path, where the compiler looks for object files.{$OBJECTPATHXXX} will add XXXto the object path.XXXcan contain one or more paths, separated by semi-colonsor colons.

For example:

{$OBJECTPATH ../inc;../i386}

{$L strings.o}

will add the directories../inc and../i386 to the object path of the compiler. The compiler will lookfor the filestrings.o in both these directories, and will link the first found file in the program. Thisdirective is equivalent to the-Fo command-line switch.

Caution is in order when using this directive: If you distribute files, the places of the files may not bethe same as on your machine; moreover, the directory structure may be different. In general it wouldbe fair to say that you should avoid usingabsolutepaths, instead userelativepaths, as in the exampleabove. Only use this directive if you are certain of the places where the files reside. If you are notsure, it is better practice to use makefiles and makefile variables.

$S : Stack checkingThe {$S+} directive tells the compiler to generate stack checking code. This generates code tocheck if a stack overflow occurred, i.e. to see whether the stack has grown beyond its maximallyallowed size. If the stack grows beyond the maximum size, then a run-time error is generated, andthe program will exit with exit code 202.

Specifying{$S-} will turn generation of stack-checking code off.

The command-line compiler switch-Ct has the same effect as the{$S+} directive.

By default, no stack checking is performed.

$UNITPATH : Specify unit path.This option serves to specify the unit path, where the compiler looks for unit files.{$UNITPATHXXX} will add XXXto the unit path.XXXcan contain one or more paths, separated by semi-colonsor colons.

For example:

{$UNITPATH ../units;../i386/units}

Uses strings;

will add the directories../units and../i386/units to the unit path of the compiler. The compiler willlook for the filestrings.ppu in both these directories, and will link the first found file in the program.This directive is equivalent to the-Fu command-line switch.

Caution is in order when using this directive: If you distribute files, the places of the files may not bethe same as on your machine; moreover, the directory structure may be different. In general it would

30

Page 32: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 1. COMPILER DIRECTIVES

be fair to say that you should avoid usingabsolutepaths, instead userelativepaths, as in the exampleabove. Only use this directive if you are certain of the places where the files reside. If you are notsure, it is better practice to use makefiles and makefile variables.

$Wor $STACKFRAMES: Generate stackframesThe{$W} switch directove controls the generation of stackframes. In the on state, the compiler willgenerate a stackframe for every procedure or function.

In the off state, the compiler will omit the generation of a stackframe if the following conditions aresatisfied:

• The procedure has no parameters.

• The procedure has no local variables.

• If the procedure is not anassembler procedure, it must not have aasm ...end; block.

• it is not a constuctor or desctructor.

If these conditions are satisfied, the stack frame will be omitted.

$Y or $REFERENCEINFO: Insert Browser informationThis switch controls the generation of browser inforation. It is recognized for compatibility withTurbo Pascal and Delphi only, as Browser information generation is not yet fully supported.

31

Page 33: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 2

Using conditionals, messages andmacros

The Free Pascal compiler supports conditionals as in normal Turbo Pascal. It does, however, morethan that. It allows you to make macros which can be used in your code, and it allows you to definemessages or errors which will be displayed when compiling.

2.1 Conditionals

The rules for using conditional symbols are the same as under Turbo Pascal. Defining a symbol goesas follows:

{$define Symbol}

From this point on in your code, the compiler knows the symbolSymbol . Symbols are, like thePascal language, case insensitive.

You can also define a symbol on the command line. the-dSymbol option defines the symbolSymbol . You can specify as many symbols on the command line as you want.

Undefining an existing symbol is done in a similar way:

{$undef Symbol}

If the symbol didn’t exist yet, this doesn’t do anything. If the symbol existed previously, the symbolwill be erased, and will not be recognized any more in the code following the{$undef \dots}statement.

You can also undefine symbols from the command line with the-u command-line switch.

To compile code conditionally, depending on whether a symbol is defined or not, you can enclosethe code in a{$ifdef Symbol} . . .{$endif} pair. For instance the following code will neverbe compiled:

{$undef MySymbol}{$ifdef Mysymbol}

DoSomething;...

{$endif}

32

Page 34: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 2. USING CONDITIONALS, MESSAGES AND MACROS

Similarly, you can enclose your code in a{$ifndef Symbol} . . .{$endif} pair. Then thecode between the pair will only be compiled when the used symbol doesn’t exist. For example, inthe following example, the call to theDoSomething will always be compiled:

{$undef MySymbol}{$ifndef Mysymbol}

DoSomething;...

{$endif}

You can combine the two alternatives in one structure, namely as follows

{$ifdef Mysymbol}DoSomething;

{$else}DoSomethingElse

{$endif}

In this example, ifMySymbol exists, then the call toDoSomething will be compiled. If it doesn’texist, the call toDoSomethingElse is compiled.

Except for the Turbo Pascal constructs the Free Pascal compiler also supports a stronger conditionalcompile mechanism: The{$if} construct.

The prototype of this construct is as follows:

{$if expr}CompileTheseLines;

{$else}BetterCompileTheseLines;

{$endif}

In this directiveexpr is a Pascal expression which is evaluated using strings, unless both parts ofa comparision can be evaluated as numbers, in which case they are evaluated using numbers1. Ifthe complete expression evaluates to’0’ , then it is considered false and rejected. Otherwise it isconsidered true and accepted. This may have unexpected consequences:

{$if 0}

will evaluate toFalse and be rejected, while

{$if 00}

will evaluate toTrue .

You can use any Pascal operator to construct your expression:=, <>, >, <, >=, <=, AND,NOT, ORand you can use round brackets to change the precedence of the operators.

The following example shows you many of the possibilities:

{$ifdef fpc}

vary : longint;

{$else fpc}

1Otherwise{$if 8>54} would evaluate toTrue

33

Page 35: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 2. USING CONDITIONALS, MESSAGES AND MACROS

varz : longint;

{$endif fpc}

varx : longint;

begin

{$if (fpc_version=0) and (fpc_release>6) and (fpc_patch>4)}{$info At least this is version 0.9.5}{$else}{$fatal Problem with version check}{$endif}

{$define x:=1234}{$if x=1234}{$info x=1234}{$else}{$fatal x should be 1234}{$endif}

{$if 12asdf and 12asdf}{$info $if 12asdf and 12asdf is ok}{$else}{$fatal $if 12asdf and 12asdf rejected}{$endif}

{$if 0 or 1}{$info $if 0 or 1 is ok}{$else}{$fatal $if 0 or 1 rejected}{$endif}

{$if 0}{$fatal $if 0 accepted}{$else}{$info $if 0 is ok}{$endif}

{$if 12=12}{$info $if 12=12 is ok}{$else}{$fatal $if 12=12 rejected}{$endif}

{$if 12<>312}{$info $if 12<>312 is ok}{$else}{$fatal $if 12<>312 rejected}{$endif}

34

Page 36: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 2. USING CONDITIONALS, MESSAGES AND MACROS

{$if 12<=312}{$info $if 12<=312 is ok}{$else}{$fatal $if 12<=312 rejected}{$endif}

{$if 12<312}{$info $if 12<312 is ok}{$else}{$fatal $if 12<312 rejected}{$endif}

{$if a12=a12}{$info $if a12=a12 is ok}{$else}{$fatal $if a12=a12 rejected}{$endif}

{$if a12<=z312}{$info $if a12<=z312 is ok}{$else}{$fatal $if a12<=z312 rejected}{$endif}

{$if a12<z312}{$info $if a12<z312 is ok}{$else}{$fatal $if a12<z312 rejected}{$endif}

{$if not(0)}{$info $if not(0) is OK}{$else}{$fatal $if not(0) rejected}{$endif}

{$info *************************************************}{$info * Now have to follow at least 2 error messages: *}{$info *************************************************}

{$if not(0}{$endif}

{$if not(<}{$endif}

end.

As you can see from the example, this construct isn’t useful when used with normal symbols, only ifyou use macros, which are explained in section2.3, page37. They can be very useful. When tryingthis example, you must switch on macro support, with the-Sm command-line switch.

35

Page 37: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 2. USING CONDITIONALS, MESSAGES AND MACROS

Predefined symbolsThe Free Pascal compiler defines some symbols before starting to compile your program or unit.You can use these symbols to differentiate between different versions of the compiler, and betweendifferent compilers. To get all the possible defines when starting compilation, see appendixG

Remark: Symbols, even when they’re defined in the interface part of a unit, are not available outside that unit.

2.2 Messages

Free Pascal lets you define normal, warning and error messages in your code. Messages can be usedto display useful information, such as copyright notices, a list of symbols that your code reacts onetc.

Warnings can be used if you think some part of your code is still buggy, or if you think that a certaincombination of symbols isn’t useful.

Error messages can be useful if you need a certain symbol to be defined, to warn that a certainvariable isn’t defined, or when the compiler version isn’t suitable for your code.

The compiler treats these messages as if they were generated by the compiler. This means that if youhaven’t turned on warning messages, the warning will not be displayed. Errors are always displayed,and the compiler stops if 50 errors have occurred. After a fatal error, the compiler stops at once.

For messages, the syntax is as follows:

{$Message Message text}

or

{$Info Message text}

For notes:

{$Note Message text}

For warnings:

{$Warning Warning Message text}

For errors:

{$Error Error Message text}

Lastly, for fatal errors:

{$Fatal Error Message text}

or

{$Stop Error Message text}

The difference between$Error and$FatalError or $Stop messages is that when the compilerencounters an error, it still continues to compile. With a fatal error, the compiler stops.

Remark: You cannot use the ’} ’ character in your message, since this will be treated as the closing brace ofthe message.

As an example, the following piece of code will generate an error when the symbolRequiredVarisn’t defined:

36

Page 38: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 2. USING CONDITIONALS, MESSAGES AND MACROS

{$ifndef RequiredVar}{$Error Requiredvar isn’t defined !}{$endif}

But the compiler will continue to compile. It will not, however, generate a unit file or a program(since an error occurred).

2.3 Macros

Macros are very much like symbols in their syntax, the difference is that macros have a value whereasa symbol simply is defined or is not defined. If you want macro support, you need to specify the-Smcommand-line switch, otherwise your macro will be regarded as a symbol.

Defining a macro in your program is done in the same way as defining a symbol; in a{$define}preprocessor statement2:

{$define ident:=expr}

If the compiler encountersident in the rest of the source file, it will be replaced immediately byexpr . This replacement works recursive, meaning that when the compiler expanded one of yourmacros, it will look at the resulting expression again to see if another replacement can be made. Youneed to be careful with this, because an infinite loop can occur in this manner.

Here are two examples which illustrate the use of macros:

{$define sum:=a:=a+b;}...sum { will be expanded to ’a:=a+b;’

remark the absence of the semicolon}...{$define b:=100}sum { Will be expanded recursively to a:=a+100; }...

The previous example could go wrong:

{$define sum:=a:=a+b;}...sum { will be expanded to ’a:=a+b;’

remark the absence of the semicolon}...{$define b=sum} { DON’T do this !!!}sum { Will be infinitely recursively expanded \dots }...

On my system, the last example results in a heap error, causing the compiler to exit with a run-timeerror 203.

Remark: Macros defined in the interface part of a unit are not available outside that unit! They can just beused as a notational convenience, or in conditional compiles.

By default the compiler predefines three macros, containing the version number, the release numberand the patch number. They are listed in table (2.1).

Remark: Don’t forget that macros support isn’t on by default. You need to compile with the-Sm command-line switch.

2In compiler versions older than 0.9.8, the assignment operator for a macros wasn’t:= but=

37

Page 39: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 2. USING CONDITIONALS, MESSAGES AND MACROS

Table 2.1: Predefined macros

Symbol ContainsFPC_VERSION The version number of the compiler.FPC_RELEASE The release number of the compiler.FPC_PATCH The patch number of the compiler.

38

Page 40: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 3

Using Assembly language

Free Pascal supports inserting assembler statements in your code. The mechanism for this is thesame as under Turbo Pascal. There are, however some substantial differences, as will be explainedin the following sections.

3.1 Intel 80x86 Inline assembler

Intel syntaxFree Pascal supports Intel syntax for the Intel family of Ix86 processors in it’sasm blocks.

The Intel syntax in yourasm block is converted to AT&T syntax by the compiler, after which itis inserted in the compiled source. The supported assembler constructs are a subset of the normalassembly syntax. In what follows we specify what constructs are not supported in Free Pascal, butwhich exist in Turbo Pascal:

• TheTBYTEqualifier is not supported.

• The& identifier override is not supported.

• TheHIGH operator is not supported.

• TheLOWoperator is not supported.

• TheOFFSETandSEGoperators are not supported. UseLEA and the variousLxx instructionsinstead.

• Expressions with constant strings are not allowed.

• Access to record fields via parenthesis is not allowed

• Typecasts with normal pascal types are not allowed, only recognized assembler typecasts areallowed. Example:

mov al, byte ptr MyWord -- allowed,mov al, byte(MyWord) -- allowed,mov al, shortint(MyWord) -- not allowed.

• Pascal type typecasts on constants are not allowed. Example:

const s= 10; const t = 32767;

39

Page 41: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 3. USING ASSEMBLY LANGUAGE

in Turbo Pascal:

mov al, byte(s) -- useless typecast.mov al, byte(t) -- syntax error!

In this parser, either of those cases will give out a syntax error.

• Constant references expressions with constants only are not allowed (in all cases they do notwork in protected mode, underLINUX i386). Examples:

mov al,byte ptr [’c’] -- not allowed.mov al,byte ptr [100h] -- not allowed.

(This is due to the limitation of Turbo Assembler).

• Brackets within brackets are not allowed

• Expressions with segment overrides fully in brackets are presently not supported, but they caneasily be implemented in BuildReference if requested. Example:

mov al,[ds:bx] -- not allowed

use instead:

mov al,ds:[bx]

• Possible allowed indexing are as follows:

– Sreg:[REG+REG*SCALING+/-disp]

– SReg:[REG+/-disp]

– SReg:[REG]

– SReg:[REG+REG+/-disp]

– SReg:[REG+REG*SCALING]

WhereSreg is optional and specifies the segment override.Notes:

1. The order of terms is important contrary to Turbo Pascal.

2. The Scaling value must be a value, and not an identifier to a symbol. Examples:

const myscale = 1;...mov al,byte ptr [esi+ebx*myscale] -- not allowed.

use:

mov al, byte ptr [esi+ebx*1]

• Possible variable identifier syntax is as follows: (Id = Variable or typed constant identifier.)

1. ID

2. [ID]

3. [ID+expr]

4. ID[expr]

Possible fields are as follow:

1. ID.subfield.subfield ...

40

Page 42: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 3. USING ASSEMBLY LANGUAGE

2. [ref].ID.subfield.subfield ...

3. [ref].typename.subfield ...

• Local abels: Contrary to Turbo Pascal, local labels, must at least contain one character afterthe local symbol indicator. Example:

@: -- not allowed

use instead, for example:

@1: -- allowed

• Contrary to Turbo Pascal local references cannot be used as references, only as displacements.Example:

lds si,@mylabel -- not allowed

• Contrary to Turbo Pascal,SEGCS, SEGDS, SEGESandSEGSSsegment overrides are presentlynot supported. (This is a planned addition though).

• Contrary to Turbo Pascal where memory sizes specifiers can be practically anywhere, the FreePascal Intel inline assembler requires memory size specifiers to be outside the brackets. Ex-ample:

mov al,[byte ptr myvar] -- not allowed.

use:

mov al,byte ptr [myvar] -- allowed.

• Base and Index registers must be 32-bit registers. (limitation of the GNU Assembler).

• XLAT is equivalent toXLATB.

• Only Single and Double FPU opcodes are supported.

• Floating point opcodes are currently not supported (except those which involve only floatingpoint registers).

The Intel inline assembler supports the following macros:

@Result represents the function result return value.

Self represents the object method pointer in methods.

AT&T SyntaxFree Pascal uses theGNU as assembler to generate its object files for the Intel Ix86 processors. SincetheGNU assembler uses AT&T assembly syntax, the code you write should use the same syntax. Thedifferences between AT&T and Intel syntax as used in Turbo Pascal are summarized in the following:

• The opcode names include the size of the operand. In general, one can say that the AT&Topcode name is the Intel opcode name, suffixed with a ’l ’, ’ w’ or ’ b’ for, respectively, longint(32 bit), word (16 bit) and byte (8 bit) memory or register references. As an example, the Intelconstruct ’mov al bl is equivalent to the AT&T style ’movb %bl,%al ’ instruction.

41

Page 43: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 3. USING ASSEMBLY LANGUAGE

• AT&T immediate operands are designated with ’$’, while Intel syntax doesn’t use a prefix forimmediate operands. Thus the Intel construct ’mov ax, 2 ’ becomes ’movb $2, %al ’ inAT&T syntax.

• AT&T register names are preceded by a ’%’ sign. They are undelimited in Intel syntax.

• AT&T indicates absolute jump/call operands with ’* ’, Intel syntax doesn’t delimit these ad-dresses.

• The order of the source and destination operands are switched. AT&T syntax uses ’Source,Dest ’, while Intel syntax features ’Dest, Source ’. Thus the Intel construct ’add eax,4’ transforms to ’addl $4, %eax ’ in the AT&T dialect.

• Immediate long jumps are prefixed with the ’l ’ prefix. Thus the Intel ’call/jmp section:offset’is transformed to ’lcall/ljmp $section,$offset ’. Similarly the far return is ’lret ’,instead of the Intel ’ret far ’.

• Memory references are specified differently in AT&T and Intel assembly. The Intel indirectmemory reference

Section:[Base + Index*Scale + Offs]

is written in AT&T syntax as:

Section:Offs(Base,Index,Scale)

WhereBase andIndex are optional 32-bit base and index registers, andScale is used tomultiply Index . It can take the values 1,2,4 and 8. TheSection is used to specify anoptional section register for the memory operand.

More information about the AT&T syntax can be found in theas manual, although the followingdifferences with normal AT&T assembly must be taken into account:

• Only the following directives are presently supported:

.byte

.word

.long

.ascii

.asciz

.globl

• The following directives are recognized but are not supported:

.align

.lcomm

Eventually they will be supported.

• Directives are case sensitive, other identifiers are not case sensitive.

• Contrary to GAS local labels/symbolsmuststart with.L

• The not operator’!’ is not supported.

• String expressions in operands are not supported.

• CBTW,CWTL,CWTD and CLTD are not supported, use the normal intel equivalents instead.

42

Page 44: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 3. USING ASSEMBLY LANGUAGE

• Constant expressions which represent memory references are not allowed even though constantimmediate value expressions are supported. Examples:

const myid = 10;...movl $myid,%eax -- allowedmovl myid(%esi),%eax -- not allowed.

• When the.globl directive is found, the symbol following it is made public and is immedi-ately emitted. Therefore label names with this name will be ignored.

• Only Single and Double FPU opcodes are supported.

The AT&T inline assembler supports the following macros:

__RESULT represents the function result return value.

__SELF represents the object method pointer in methods.

__OLDEBP represents the old base pointer in recusrive routines.

3.2 Motorola 680x0 Inline assembler

The inline assembler reader for the Motorola 680x0 family of processors, uses the Motorola Assem-bler syntax (q.v). A few differences do exit:

• Local labels start with the @ character, such as

@MyLabel:

• The XDEFdirective in an assembler block will make the symbol available publicly with thespecified name (this name is case sensitive)

• The DB, DW, DDdirectives can only be used to declare constants which will be stored in thecode segment.

• TheAlign directive is not supported.

• Arithmetic operations on constant expression use the same operands as the intel version (e.g :AND, XOR...)

• Segment directives are not supported

• Only 68000 and a subset of 68020 opcodes are currently supported

The inline assembler supports the following macros:

@Result represents the function result return value.

Self represents the object method pointer in methods.

43

Page 45: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 3. USING ASSEMBLY LANGUAGE

3.3 Signaling changed registers

When the compiler uses variables, it sometimes stores them, or the result of some calculations, inthe processor registers. If you insert assembler code in your program that modifies the processorregisters, then this may interfere with the compiler’s idea about the registers. To avoid this problem,Free Pascal allows you to tell the compiler which registers have changed. The compiler will thenavoid using these registers. Telling the compiler which registers have changed is done by specifyinga set of register names behind an assembly block, as follows:

asm...

end [’R1’, ... ,’Rn’];

HereR1 to Rn are the names of the registers you modify in your assembly code.

As an example:

asmmovl BP,%eaxmovl 4(%eax),%eaxmovl %eax,__RESULTend [’EAX’];

This example tells the compiler that theEAXregister was modified.

44

Page 46: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 4

Generated code

The Free Pascal compiler relies on the assembler to make object files. It generates just the assemblylanguage file. In the following two sections, we discuss what is generated when you compile a unitor a program.

4.1 Units

When you compile a unit, the Free Pascal compiler generates 2 files:

1. A unit description file.

2. An assembly language file.

The assembly language file contains the actual source code for the statements in your unit, and thenecessary memory allocations for any variables you use in your unit. This file is converted by theassembler to an object file (with extension.o) which can then be linked to other units and yourprogram, to form an executable.

By default, the assembly file is removed after it has been compiled. Only in the case of the-scommand-line option, the assembly file will be left on disk, so the assembler can be called later. Youcan disable the erasing of the assembler file with the-a switch.

The unit file contains all the information the compiler needs to use the unit:

1. Other used units, both in interface and implementation.

2. Types and variables from the interface section of the unit.

3. Function declarations from the interface section of the unit.

4. Some debugging information, when compiled with debugging.

The detailed contents and structure of this file are described in the first appendix. You can examine aunit description file using theppudump program, which shows the contents of the file.

If you want to distribute a unit without source code, you must provide both the unit description fileand the object file.

You can also provide a C header file to go with the object file. In that case, your unit can be used bysomeone who wishes to write his programs in C. However, you must make this header file yourselfsince the Free Pascal compiler doesn’t make one for you.

45

Page 47: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 4. GENERATED CODE

4.2 Programs

When you compile a program, the compiler produces again 2 files:

1. An assembly language file containing the statements of your program, and memory allocationsfor all used variables.

2. A linker response file. This file contains a list of object files the linker must link together.

The link response file is, by default, removed from the disk. Only when you specify the-s command-line option or when linking fails, then the file is left on the disk. It is namedlink.res.

The assembly language file is converted to an object file by the assembler, and then linked togetherwith the rest of the units and a program header, to form your final program.

The program header file is a small assembly program which provides the entry point for the program.This is where the execution of your program starts, so it depends on the operating system, becauseoperating systems pass parameters to executables in wildly different ways.

It’s name isprt0.o, and the source file resides inprt0.as or some variant of this name. It usuallyresided where the system unit source for your system resides. It’s main function is to save theenvironment and command-line arguments and set up the stack. Then it calls the main program.

46

Page 48: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 5

Intel MMX support

5.1 What is it about?

Free Pascal supports the new MMX (Multi-Media extensions) instructions of Intel processors. Theidea of MMX is to process multiple data with one instruction, for example the processor can addsimultaneously 4 words. To implement this efficiently, the Pascal language needs to be extended. SoFree Pascal allows to add for example twoarray[0..3] of word , if MMX support is switchedon. The operation is done by theMMXunit and allows people without assembler knowledge to takeadvantage of the MMX extensions.

Here is an example:

usesMMX; { include some predefined data types }

const{ tmmxword = array[0..3] of word;, declared by unit MMX }w1 : tmmxword = (111,123,432,4356);w2 : tmmxword = (4213,63456,756,4);

varw3 : tmmxword;l : longint;

beginif is_mmx_cpu then { is_mmx_cpu is exported from unit mmx }

begin{$mmx+} { turn mmx on }

w3:=w1+w2;{$mmx-}

endelse

beginfor i:=0 to 3 do

w3[i]:=w1[i]+w2[i];end;

end.

47

Page 49: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 5. INTEL MMX SUPPORT

5.2 Saturation support

One important point of MMX is the support of saturated operations. If a operation would causean overflow, the value stays at the highest or lowest possible value for the data type: If you usebyte values you get normally 250+12=6. This is very annoying when doing color manipulations orchanging audio samples, when you have to do a word add and check if the value is greater than 255.The solution is saturation: 250+12 gives 255. Saturated operations are supported by theMMXunit. Ifyou want to use them, you have simple turn the switch saturation on:$saturation+

Here is an example:

Program SaturationDemo;{

example for saturation, scales data (for example audio)with 1.5 with rounding to negative infinity

}uses mmx;

varaudio1 : tmmxword;i: smallint;

consthelpdata1 : tmmxword = ($c000,$c000,$c000,$c000);helpdata2 : tmmxword = ($8000,$8000,$8000,$8000);

begin{ audio1 contains four 16 bit audio samples }

{$mmx+}{ convert it to $8000 is defined as zero, multiply data with 0.75 }audio1:=(audio1+helpdata2)*(helpdata1);

{$saturation+}{ avoid overflows (all values>$7fff becomes $ffff) }audio1:=(audio1+helpdata2)-helpdata2;

{$saturation-}{ now mupltily with 2 and change to integer }for i:=0 to 3 do

audio1[i] := audio1[i] shl 1;audio1:=audio1-helpdata2;

{$mmx-}end.

5.3 Restrictions of MMX support

In the beginning of 1997 the MMX instructions were introduced in the Pentium processors, so mul-titasking systems wouldn’t save the newly introduced MMX registers. To work around that problem,Intel mapped the MMX registers to the FPU register.

The consequence is that you can’t mix MMX and floating point operations. After using MMXoperations and before using floating point operations, you have to call the routineEMMSof theMMXunit. This routine restores the FPU registers.

Careful: The compiler doesn’t warn if you mix floating point and MMX operations, so be careful.

The MMX instructions are optimized for multi media (what else?). So it isn’t possible to perform

48

Page 50: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 5. INTEL MMX SUPPORT

each operation, some operations give a type mismatch, see section5.4for the supported MMX oper-ations

An important restriction is that MMX operations aren’t range or overflow checked, even when youturn range and overflow checking on. This is due to the nature of MMX operations.

TheMMXunit must always be used when doing MMX operations because the exit code of this unitclears the MMX unit. If it wouldn’t do that, other program will crash. A consequence of this is thatyou can’t use MMX operations in the exit code of your units or programs, since they would interferewith the exit code of theMMXunit. The compiler can’t check this, so you are responsible for this!

5.4 Supported MMX operations

The following operations are supported in the compiler when MMX extensions are enabled:

• addition (+)

• subtraction (- )

• multiplication(* )

• logical exclusive or (xor )

• logical and (and )

• logical or (or )

• sign change (- )

5.5 Optimizing MMX support

Here are some helpful hints to get optimal performance:

• TheEMMScall takes a lot of time, so try to seperate floating point and MMX operations.

• Use MMX only in low level routines because the compiler saves all used MMX registers whencalling a subroutine.

• The NOT-operator isn’t supported natively by MMX, so the compiler has to generate a work-around and this operation is inefficient.

• Simple assignements of floating point numbers don’t access floating point registers, so youneed no call to theEMMSprocedure. Only when doing arithmetic, you need to call theEMMSprocedure.

49

Page 51: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 6

Code issues

This chapter gives detailed information on the generated code by Free Pascal. It can be useful towrite external object files which will be linked to Free Pascal created code blocks.

6.1 Register Conventions

The compiler has different register conventions, depending on the target processor used; some of theregisters have specific uses during the code generation. The following section describes the genericnames of the registers on a platform per platform basis. It also indicates what registers are used asscratch registers, and which can be freely used in assembler blocks.

accumulator registerThe accumulator register is at least a 32-bit integer hardware register, and is used to return results offunction calls which return integral values.

accumulator 64-bit registerThe accumulator 64-bit register is used in 32-bit environments and is defined as the group of registerswhich will be used when returning 64-bit integral results in function calls. This is a register pair.

float result registerThis register is used for returning floating point values from functions.

self registerThe self register contains a pointer to the actual object or class. This register gives access to the dataof the object or class, and the VMT pointer of that object or class.

frame pointer registerThe frame pointer register is used to access parameters in subroutines, as well as to access localvariables. References to the pushed prameters and local variables are constructed using the frame

50

Page 52: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

pointer.1.

stack pointer registerThe stack pointer is used to give the address of the stack area, where the local variables and paramet-ers to subroutines are stored.

scratch registersScratch registers are those which can be used in assembler blocks, or in external object files withoutrequiring any saving before usage.

Processor mapping of registersThis indicates what registers are used for what purposes on each of the processors supported by FreePascal. It also indicates which registers can be used as scratch registers.

Intel 80x86 version

Table 6.1: Intel 80x86 Register table

Generic register name CPU Register nameaccumulator EAXaccumulator (64-bit) high / low EDX:EAXfloat result FP(0)self ESIframe pointer EBPstack pointer ESPscratch regs. N/A

Motorola 680x0 version

Table 6.2: Motorola 680x0 Register table

Generic register name CPU Register nameaccumulator D02

accumulator (64-bit) high / low D0:D1float result FP03

self A5frame pointer A6stack pointer A7scratch regs. D0, D1, A0, A1, FP0, FP1

1The frame pointer is not available on all platforms2For compatibility with some C compilers, when the function result is a pointer and is declared with the cdecl convention,

the result is also stored in the A0 register3On simulated FPU’s the result is returned in D0

51

Page 53: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

6.2 Name mangling

Contrary to most C compilers and assemblers, all labels generated to pascal variables and routineshave mangled names4. This is done so that the compiler can do stronger type checking when parsingthe pascal code. It also permits function and procedure overloading.

Mangled names for data blocksThe rules for mangled names for variables and typed constants are as follows:

• All variable names are converted to upper case

• Variables in the main program or private to a unit have an _ prepended to their names

• Typed constants in the main program have an TC__ prepended to their names

• Public variables in a unit have their unit name prepended to them : U_UNITNAME_

• Public and private typed constants in a unit have their unit name prepended to them :TC__UNITNAME$$

Currently, in Free Pascal v1.0, if you declare a variable in unit nametunit , with the name_a , andyou declare the same variable with namea in unit nametunit_ , you will get the same mangledname. This is a limitation of the compiler which will be fixed in release v1.1.

Examples

unit testvars;

interface

constpublictypedconst : integer = 0;

varpublicvar : integer;

implementationconst

privatetypedconst : integer = 1;var

privatevar : integer;

end.

Will give the following assembler output under GNU as :

.file "testvars.pas"

.text

.data

4This can be avoided by using thealias or cdecl modifiers

52

Page 54: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

# [6] publictypedconst : integer = 0;.globl TC__TESTVARS$$_PUBLICTYPEDCONSTTC__TESTVARS$$_PUBLICTYPEDCONST:.short 0# [12] privatetypedconst : integer = 1;TC__TESTVARS$$_PRIVATETYPEDCONST:.short 1

.bss# [8] publicvar : integer;.comm U_TESTVARS_PUBLICVAR,2# [14] privatevar : integer;.lcomm _PRIVATEVAR,2

Mangled names for code blocksThe rules for mangled names for routines are as follows:

• All routine names are converted to upper case.

• Routines in a unit have their unit name prepended to them : _UNITNAME$$_

• All Routines in the main program have a _ prepended to them.

• All parameters in a routine are mangled using the type of the parameter (in uppercase) prepen-ded by the $ character. This is done in left to right order for each parameter of the routine.

• Objects and classes use special mangling : The class type or object type is given in the mangledname; The mangled name is as follows: _$$_TYPEDECL_$$ optionally preceded by mangledname of the unit and finishing with the method name.

The following constructs

unit testman;

interfacetype

myobject = objectconstructor init;procedure mymethod;

end;

implementation

constructor myobject.init;beginend;

procedure myobject.mymethod;beginend;

function myfunc: pointer;begin

53

Page 55: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

end;

procedure myprocedure(var x: integer; y: longint; z : pchar);beginend;

end.

will result in the following assembler file for the Intel 80x86 target:

.file "testman.pas"

.text

.balign 16

.globl _TESTMAN$$_$$_MYOBJECT_$$_INIT_TESTMAN$$_$$_MYOBJECT_$$_INIT:pushl %ebpmovl %esp,%ebpsubl $4,%espmovl $0,%edicall FPC_HELP_CONSTRUCTORjz .L5jmp .L7.L5:movl 12(%ebp),%esimovl $0,%edicall FPC_HELP_FAIL.L7:movl %esi,%eaxtestl %esi,%esileaveret $8.balign 16.globl _TESTMAN$$_$$_MYOBJECT_$$_MYMETHOD_TESTMAN$$_$$_MYOBJECT_$$_MYMETHOD:pushl %ebpmovl %esp,%ebpleaveret $4.balign 16_TESTMAN$$_MYFUNC:pushl %ebpmovl %esp,%ebpsubl $4,%espmovl -4(%ebp),%eaxleaveret.balign 16_TESTMAN$$_MYPROCEDURE$INTEGER$LONGINT$PCHAR:pushl %ebpmovl %esp,%ebpleaveret $12

54

Page 56: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

Modifying the mangled namesTo make the symbols externally accessible, it is possible to give nicknames to mangled names, or tochange the mangled name directly. Two modifiers can be used:

cdecl: A function that has acdecl modifier, will be used with C calling conventions, that is, thecaller clears the stack. Also the mangled name will be the nameexactlyas it is declared.cdecl is part of the function declaration, and hence must be present both in the interface andimplementation section of a unit.

alias: Thealias modifier can be used to assign a second assembler label to your function. Thislabel has the same name as the alias name you declared. This doesn’t modify the callingconventions of the function. In other words, thealias modifier allows you to specify anothername (a nickname) for your function or procedure.

The prototype for an aliased function or procedure is as follows:

Procedure AliasedProc; alias : ’AliasName’;

The procedureAliasedProc will also be known asAliasName . Take care, the name youspecify is case sensitive (as C is).

Furthermore, theexports section of a library is also used to declare the names that will be exportedby the shared library. The names in the exports section are case-sensitive (while the actual declarationof the routine is not). For more information on the creating shared libraries, chapter11, page95.

6.3 Calling mechanism

Procedures and Functions are called with their parameters on the stack. Contrary to Turbo Pascal,allparameters are pushed on the stack, and they are pushedright to left, instead of left to right for TurboPascal. This is especially important if you have some assembly subroutines in Turbo Pascal whichyou would like to translate to Free Pascal.

Function results are returned in the accumulator, if they fit in the register. Methods calls (fromeither objects or clases) have an additional invisible parameter which isself . This parameter is theleftmost parameter within a method call (it is therefore the last parameter passed to the method).

When the procedure or function exits, it clears the stack.

Other calling methods are available for linking with external object files and libraries, these aresummarized in table (6.3). The first column lists the modifier you specify for a procedure declaration.The second one lists the order the paramaters are pushed on the stack. The third column specifieswho is responsible for cleaning the stack: the caller or the called function. The alignment columnindicates the alignment of the parameters sent to the stack area. Finally, the fifth column indicates ifany registers are saved in the entry code of the subroutine.

More about this can be found in chapter7, page60 on linking. Information on GCC registers saved,GCC stack alignment and general stack alignment on an operating system basis can be found inAppendixH. The register modifier is currently not supported, and maps to the default callingconvention.

Furthermore, thesaveregisters modifier can be used with any of the calling mechanism spe-cifiers. Whensaveregisters is used, all registers will be saved on entry to the routine, and willbe restored upon exit. Of course, if the routine is a function, and it normally returns its retun value ina register, that register will not be saved. Also, if the self register is used, it will also neither be savednor restored.

55

Page 57: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

Table 6.3: Calling mechanisms in Free Pascal

Modifier Pushing order Stack cleaned by alignment registers saved<none> Right-to-left Function default Nonecdecl Right-to-left Caller GCC alignment GCC registersinterrupt Right-to-left Function default all registerspascal Left-to-right Function default Nonesafecall Right-to-left Function default GCC registersstdcall Right-to-left Function GCC alignment GCC registerspopstack Right-to-left Caller default Noneregister Left-to-right Caller default None

6.4 Nested procedure and functions

When a routine is declared within the scope of a procedure or function, it is said to be nested. In thiscase, an additional invisible parameter is passed to the nested routine. This additional parameter isthe frame pointer address of the calling routine. This permits the nested routine to access the localvariables and parameters of the calling routine.

The resulting stack frame after the entry code of a simple nested procedure has been executed isshown in table (6.4).

Table 6.4: Stack frame when calling a nested procedure (32-bit processors)

Offset from frame pointer What is stored+x parameters+8 Frame pointer of parent routine+4 Return address+0 Saved frame pointer

6.5 Constructor and Destructor calls

Constructor and destructors have special invisible parameters which are passed to them. These invis-ible parameters are used internally to instanciate the objects and classes.

objectsThe actual invisible declaration of an object constructoir is as follows:

constructor init(_vmt : pointer; _self : pointer ...);

Where_vmt is a pointer to the virtual method table for this object. This value is nil if a constructoris called within the object instance (such as calling an ihnerited constructor).

_self is either nil if the instance must be allocated dynamically (object is declared as pointer), orthe address of the object instance if the object is declared as a normal object (stored in the data area)or if the object instance has already been allocated.

The allocated instance (if allocated via new) (self ) is returned in the accumulator.

56

Page 58: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

The declaration of a destructor is as follows:

destructor done(_vmt : pointer; _self : pointer ...);

Where_vmt is a pointer to the virtual method table for this object. This value is nil if a destructor iscalled within the object instance (such as calling an ihnerited constructor), or if the object instance isa variable and not a pointer.

_self is the address of the object instance.

classesThe actual invisible declaration of a class constructoir is as follows:

constructor init(_vmt: pointer; flag : longint; ..);

_vmt is either nil if called from the instance or if calling an inherited constructor, otherwise it pointsto the address of the virtual method table.

Whereflag is zero if the constructor is called within the object instance or with an instance qualifierotherwise this flag is set to one.

The allocated instance (self ) is returned in the accumulator.

The declaration of a destructor is as follows:

destructor done(_self : pointer; flag : longint ...);

_self is the address of the object instance.

flag is zero if the destructor is called within the object instance or with an instance qualifier other-wise this flag is set to one.

6.6 Entry and exit code

Each Pascal procedure and function begins and ends with standard epilogue and prologue code.

Intel 80x86 standard routine prologue / epilogueStandard entry code for procedures and functions is as follows on the 80x86 architecture:

pushl %ebpmovl %esp,%ebp

The generated exit sequence for procedure and functions looks as follows:

leaveret $xx

Wherexx is the total size of the pushed parameters.

To have more information on function return values take a look at section6.1, page50.

57

Page 59: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

Motorola 680x0 standard routine prologue / epilogueStandard entry code for procedures and functions is as follows on the 680x0 architecture:

move.l a6,-(sp)move.l sp,a6

The generated exit sequence for procedure and functions looks as follows (in the default processormode):

unlk a6rtd #xx

Wherexx is the total size of the pushed parameters.

To have more information on function return values take a look at section6.1, page50.

6.7 Parameter passing

When a function or procedure is called, then the following is done by the compiler:

1. If there are any parameters to be passed to the procedure, they are pushed from right to left onthe stack.

2. If a function is called that returns a variable of typeString , Set , Record , Object orArray , then an address to store the function result in, is pushed on the stack.

3. If the called procedure or function is an object method, then the pointer toself is pushed onthe stack.

4. If the procedure or function is nested in another function or procedure, then the frame pointerof the parent procedure is pushed on the stack.

5. The return address is pushed on the stack (This is done automatically by the instruction whichcalls the subroutine).

The resulting stack frame upon entering looks as in table (6.5).

Table 6.5: Stack frame when calling a procedure (32-bit model)

Offset What is stored Optional?+x parameters Yes+12 function result Yes+8 self Yes+4 Return address No+0 Frame pointer of parent procedure Yes

Parameter alignmentEach parameter passed to a routine is guaranteed to decrement the stack pointer by a certain minimumamount. This behavior varies from one operating system to another. For example, passing a byteas a value parameter to a routine could either decrement the stack pointer by 1, 2, 4 or even 8 bytes

58

Page 60: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 6. CODE ISSUES

depending on the target operating system and processor. The minimal default stack pointer decrementvalue is given in AppendixH.

For example, on FREEBSD, all parameters passed to a routine guarantee a minimal stack decrease offour bytes per parameter, even if the parameter actually takes less then 4 bytes to store on the stack(such as passing a byte value parameter to the stack).

6.8 Processor limitations

Certain processors have limitations on the size of the parameters and local variables in routines. Thisis shown in table (6.6).

Table 6.6: Maximum limits for processors

Processor Parameters Local variablesIntel 80x86 (all) 64K No limitMotorola 68020 (default) 32K No limitMotorola 68000 32K 32K

Furthermore, the m68k compiler, in68000 mode, limits the size of data elements to 32K (arrays,records, objects, etc.). This restriction does not exist in68020 mode.

59

Page 61: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 7

Linking issues

When you only use Pascal code, and Pascal units, then you will not see much of the part that thelinker plays in creating your executable. The linker is only called when you compile a program.When compiling units, the linker isn’t invoked.

However, there are times that linking to C libraries, or to external object files created by other com-pilers may be necessary. The Free Pascal compiler can generate calls to a C function, and cangenerate functions that can be called from C (exported functions).

7.1 Using external code and variables

In general, there are 3 things you must do to use a function that resides in an external library or objectfile:

1. You must make a pascal declaration of the function or procedure you want to use.

2. You must declare the correct calling convention to use.

3. You must tell the compiler where the function resides, i.e. in what object file or what library,so the compiler can link the necessary code in.

The same holds for variables. To access a variable that resides in an external object file, you mustdeclare it, and tell the compiler where to find it. The following sections attempt to explain how to dothis.

Declaring external functions or proceduresThe first step in using external code blocks is declaring the function you want to use. Free Pascalsupports Delphi syntax, i.e. you must use theexternal directive. Theexternal directivereplaces, in effect, the code block of the function.

The external directive doesn’t specify a calling convention; it just tells the compiler that the code fora procedure or function resides in an external code block. A calling convention modifier should bedeclared if the external code blocks does not have the same calling conventions as Free Pascal. Formore information on the calling conventions section6.3, page55.

There exist four variants of the external directive:

1. A simple external declaration:

60

Page 62: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 7. LINKING ISSUES

Procedure ProcName (Args : TPRocArgs); external;

The external directive tells the compiler that the function resides in an external block ofcode. You can use this together with the{$L} or {$LinkLib} directives to link to a functionor procedure in a library or external object file. Object files are looked for in the object searchpath (set by-Fo ) and libraries are searched for in the linker path (set by-Fl ).

2. You can give theexternal directive a library name as an argument:

Procedure ProcName (Args : TPRocArgs); external ’Name’;

This tells the compiler that the procedure resides in a library with name’Name’ . This methodis equivalent to the following:

Procedure ProcName (Args : TPRocArgs);external;{$LinkLib ’Name’}

3. Theexternal can also be used with two arguments:

Procedure ProcName (Args : TPRocArgs); external ’Name’name ’OtherProcName’;

This has the same meaning as the previous declaration, only the compiler will use the name’OtherProcName’ when linking to the library. This can be used to give different names toprocedures and functions in an external library. The name of the routine is case-sensitive andshould match exactly the name of the routine in the object file.

This method is equivalent to the following code:

Procedure OtherProcName (Args : TProcArgs); external;{$LinkLib ’Name’}

Procedure ProcName (Args : TPRocArgs);

beginOtherProcName (Args);

end;

4. Lastly, onder WINDOWS andOS/2, there is a fourth possibility to specify an external function:In .DLL files, functions also have a unique number (their index). It is possible to refer to thesefuctions using their index:

Procedure ProcName (Args : TPRocArgs); external ’Name’ Index SomeIndex;

This tells the compiler that the procedureProcName resides in a dynamic link library, withindex SomeIndex.

Remark: Note that this is ONLY available under WINDOWS andOS/2.

Declaring external variablesSome libaries or code blocks have variables which they export. You can access these variables muchin the same way as external functions. To access an external variable, you declare it as follows:

VarMyVar : MyType; external name ’varname’;

61

Page 63: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 7. LINKING ISSUES

The effect of this declaration is twofold:

1. No space is allocated for this variable.

2. The name of the variable used in the assembler code isvarname . This is a case sensitivename, so you must be careful.

The variable will be accessible with it’s declared name, i.e.MyVar in this case.

A second possibility is the declaration:

Varvarname : MyType; cvar; external;

The effect of this declaration is twofold as in the previous case:

1. Theexternal modifier ensures that no space is allocated for this variable.

2. Thecvar modifier tells the compiler that the name of the variable used in the assembler codeis exactly as specified in the declaration. This is a case sensitive name, so you must be careful.

The first possibility allows you to change the name of the external variable for internal use.

As an example, let’s look at the following C file (inextvar.c):

/*Declare a variable, allocate storage*/int extvar = 12;

And the following program (inextdemo.pp):

Program ExtDemo;

{$L extvar.o}

Var { Case sensitive declaration !! }extvar : longint; cvar;external;I : longint; external name ’extvar’;

begin{ Extvar can be used case insensitive !! }Writeln (’Variable ’’extvar’’ has value: ’,ExtVar);Writeln (’Variable ’’I’’ has value: ’,i);

end.

Compiling the C file, and the pascal program:

gcc -c -o extvar.o extvar.cppc386 -Sv extdemo

Will produce a programextdemo which will print

Variable ’extvar’ has value: 12Variable ’I’ has value: 12

on your screen.

62

Page 64: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 7. LINKING ISSUES

Declaring the calling convention modifierTo make sure that all parameters are correctly passed to the external routines, you should declare itwith the correct calling convention modifier. When linking with code blocks compiled with standardC compilers (such as GCC), thecdecl modifier should be used so as to indicate that the externalroutine uses C type calling conventions. For more information on the supported calling conventions,section6.3, page55.

As might expected, external variable declarations do not require any calling convention modifier.

Declaring the external object codeLinking to an object file

Having declared the external function or variable that resides in an object file, you can use it as if itwas defined in your own program or unit. To produce an executable, you must still link the objectfile in. This can be done with the{$L file.o} directive.

This will cause the linker to link in the object filefile.o. On most systems, this filename is casesensitive. The object file is first searched in the current directory, and then the directories specifiedby the-Fo command line.

You cannot specify libraries in this way, it is for object files only.

Here we present an example. Consider that you have some assembly routine which uses the C callingconvention that calculates the nth Fibonacci number:

.text.align 4

.globl Fibonacci.type Fibonacci,@function

Fibonacci:pushl %ebpmovl %esp,%ebpmovl 8(%ebp),%edxxorl %ecx,%ecxxorl %eax,%eaxmovl $1,%ebxincl %edx

loop:decl %edxje endloopmovl %ecx,%eaxaddl %ebx,%eaxmovl %ebx,%ecxmovl %eax,%ebxjmp loop

endloop:movl %ebp,%esppopl %ebpret

Then you can call this function with the following Pascal Program:

Program FibonacciDemo;

var i : longint;

63

Page 65: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 7. LINKING ISSUES

Function Fibonacci (L : longint):longint;cdecl;external;

{$L fib.o}

beginFor I:=1 to 40 do

writeln (’Fib(’,i,’) : ’,Fibonacci (i));end.

With just two commands, this can be made into a program:

as -o fib.o fib.sppc386 fibo.pp

This example supposes that you have your assembler routine infib.s, and your Pascal program infibo.pp.

Linking to a library

To link your program to a library, the procedure depends on how you declared the external procedure.

In case you used the following syntax to declare your procedure:

Procedure ProcName (Args : TPRocArgs); external ’Name’;

You don’t need to take additional steps to link your file in, the compiler will do all that is neededfor you. On WINDOWS it will link to name.dll, on LINUX and mostUNIX ’es your program will belinked to librarylibname, which can be a static or dynamic library.

In case you used

Procedure ProcName (Args : TPRocArgs); external;

You still need to explicity link to the library. This can be done in 2 ways:

1. You can tell the compiler in the source file what library to link to using the{$LinkLib’Name’} directive:

{$LinkLib ’gpm’}

This will link to thegpm library. OnUNIX systems (such asLINUX ), you must not specify theextension or ’lib’ prefix of the library. The compiler takes care of that. On other systems (suchas WINDOWS, you need to specify the full name.

2. You can also tell the compiler on the command-line to link in a library: The-k option can beused for that. For example

ppc386 -k’-lgpm’ myprog.pp

Is equivalent to the above method, and tells the linker to link to thegpm library.

As an example; consider the following program:

64

Page 66: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 7. LINKING ISSUES

program printlength;

{$linklib c} { Case sensitive }

{ Declaration for the standard C function strlen }Function strlen (P : pchar) : longint; cdecl;external;

beginWriteln (strlen(’Programming is easy !’));

end.

This program can be compiled with:

ppc386 prlen.pp

Supposing, of course, that the program source resides inprlen.pp.

To use functions in C that have a variable number of arguments, you must compile your unit orprogram inobjfpc mode orDelphi mode, and use theArray of const argument, as in thefollowing example:

program testaocc;

{$mode objfpc}

ConstP : Pchar

= ’example’;F : Pchar

= ’This %s uses printf to print numbers (%d) and strings.’#10;

procedure printf(fm: pchar;args: array of const);cdecl;external ’c’;

beginprintf(F,[P,123]);

end.

The output of this program looks like this:

This example uses printf to print numbers (123) and strings.

7.2 Making libraries

Free Pascal supports making shared or static libraries in a straightforward and easy manner. If youwant to make static libraries for other Free Pascal programmers, you just need to provide a commandline switch. To make shared libraries, refer to the chapter11, page95. If you want C programmers tobe able to use your code as well, you will need to adapt your code a little. This process is describedfirst.

Exporting functionsWhen exporting functions from a library, there are 2 things you must take in account:

65

Page 67: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 7. LINKING ISSUES

1. Calling conventions.

2. Naming scheme.

The calling conventions are controlled by the modifierscdecl , popstack , pascal , safecall ,stdcall andregister . See section6.3, page55 for more information on the different kinds ofcalling scheme.

The naming conventions can be controlled by 2 modifiers in the case of static libraries:

• cdecl

• alias

For more information on how these different modifiers change the name mangling of the routinesection6.2, page52.

Remark: If you use in your unit functions that are in other units, or system functions, then the C program willneed to link in the object files from these units too.

Exporting variablesSimilarly as when you export functions, you can export variables. When exportig variables, oneshould only consider the names of the variables. To declare a variable that should be used by a Cprogram, one declares it with thecvar modifier:

Var MyVar : MyTpe; cvar;

This will tell the compiler that the assembler name of the variable (the one which is used by Cprograms) should be exactly as specified in the declaration, i.e., case sensitive.

It is not allowed to declare multiple variables ascvar in one statement, i.e. the following code willproduce an error:

var Z1,Z2 : longint;cvar;

Compiling librariesOnce you have your (adapted) code, with exported and other functions, you can compile your unit,and tell the compiler to make it into a library. The compiler will simply compile your unit, andperform the necessary steps to transform it into astatic or shared (dynamic ) library.

You can do this as follows, for a dynamic library:

ppc386 -CD myunit

On UNIX systems, such asLINUX , this will leave you with a filelibmyunit.so. On WINDOWS andOS/2, this will leave you withmyunit.dll. An easier way to create shared libraries is to use thelibrary keyword. For more information on creating shared libraries, chapter11, page95.

If you want a static library, you can do

ppc386 -CS myunit

This will leave you withlibmyunit.a and a filemyunit.ppu. Themyunit.ppu is the unit file neededby the Free Pascal compiler.

66

Page 68: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 7. LINKING ISSUES

The resulting files are then libraries. To make static libraries, you need theranlib or ar program onyour system. It is standard on mostUNIX systems, and is provided with thegcc compiler underDOS.For the dos distribution, a copy of ar is included in the filegnuutils.zip.

BEWARE:This command doesn’t include anything but the current unit in the library. Other units areleft out, so if you use code from other units, you must deploy them together with your library.

Unit searching strategyWhen you compile a unit, the compiler will by default always look for unit files.

To be able to differentiate between units that have been compiled as static or dynamic libraries, thereare 2 switches:

-XD: This will define the symbolFPC_LINK_DYNAMIC

-XS: This will define the symbolFPC_LINK_STATIC

Definition of one symbol will automatically undefine the other.

These two switches can be used in conjunction with the configuration filefpc.cfg. The existence ofone of these symbols can be used to decide which unit search path to set. For example, onLINUX :

# Set unit paths

#IFDEF FPC_LINK_STATIC-Up/usr/lib/fpc/linuxunits/staticunits#ENDIF#IFDEF FPC_LINK_DYNAMIC-Up/usr/lib/fpc/linuxunits/sharedunits#ENDIF

With such a configuration file, the compiler will look for it’s units in different directories, dependingon whether-XD or -XS is used.

7.3 Using smart linking

You can compile your units using smart linking. When you use smartlinking, the compiler creates aseries of code blocks that are as small as possible, i.e. a code block will contain only the code forone procedure or function.

When you compile a program that uses a smart-linked unit, the compiler will only link in the codethat you actually need, and will leave out all other code. This will result in a smaller binary, which isloaded in memory faster, thus speeding up execution.

To enable smartlinking, one can give the smartlink option on the command line:-Cx , or one can putthe{$SMARTLINK ON} directive in the unit file:

Unit Testunit

{SMARTLINK ON}Interface...

Smartlinking will slow down the compilation process, especially for large units.

67

Page 69: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 7. LINKING ISSUES

When a unitfoo.pp is smartlinked, the name of the codefile is changed tolibfoo.a.

Technically speaking, the compiler makes small assembler files for each procedure and function inthe unit, as well as for all global defined variables (whether they’re in the interface section or not). Itthen assembles all these small files, and usesar to collect the resulting object files in one archive.

Smartlinking and the creation of shared (or dynamic) libraries are mutually exclusive, that is, if youturn on smartlinking, then the creation of shared libraries is turned of. The creation of static librariesis still possible. The reason for this is that it has little sense in making a smartlinked dynamicallibrary. The whole shared library is loaded into memory anyway by the dynamic linker (or theoperating system), so there would be no gain in size by making it smartlinked.

68

Page 70: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 8

Memory issues

8.1 The memory model.

The Free Pascal compiler issues 32-bit or 64-bit code. This has several consequences:

• You need a 32-bit or 64-bit processor to run the generated code. The compiler functions on a286 when you compile it using Turbo Pascal, but the generated programs cannot be assembledor executed.

• You don’t need to bother with segment selectors. Memory can be addressed using a single32-bit (on 32-bit processors) or 64-bit (on 64-bit processors with 64-bit addressing) pointer.The amount of memory is limited only by the available amount of (virtual) memory on yourmachine.

• The structures you define are unlimited in size. Arrays can be as long as you want. You canrequest memory blocks from any size.

The fact that 16-bit code is no longer used, means that some of the older Turbo Pascal constructs andfunctions are obsolete. The following is a list of functions which shouldn’t be used anymore:

Seg() : Returned the segment of a memory address. Since segments have no more meaning, zero isreturned in the Free Pascal run-time library implementation ofSeg.

Ofs() : Returned the offset of a memory address. Since segments have no more meaning, the com-plete address is returned in the Free Pascal implementation of this function. This has as aconsequence that the return type islongint or int64 instead ofWord.

Cseg(), Dseg(): Returned, respectively, the code and data segments of your program. This returnszero in the Free Pascal implementation of the system unit, since both code and data are in thesame memory space.

Ptr : Accepted a segment and offset from an address, and would return a pointer to this address.This has been changed in the run-time library, it now simply returns the offset.

memw and mem : These arrays gave access to theDOS memory. Free Pascal supports them on thego32v2 platform, they are mapped intoDOS memory space. You need thego32 unit for this.On other platforms, they arenotsupported

You shouldn’t use these functions, since they are very non-portable, they’re specific toDOS and the80x86 processor. The Free Pascal compiler is designed to be portable to other platforms, so youshould keep your code as portable as possible, and not system specific. That is, unless you’re writingsome driver units, of course.

69

Page 71: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

8.2 Data formats

This section gives information on the storage space occupied by the different possible types in FreePascal. Information on internal alignment will also be given.

integer typesThe storage size of the default integer types are given inReference guide. In the case of user defined-types, the storage space occupied depends on the bounds of the type:

• If both bounds are within range -128..127, the variable is stored as a shortint (signed 8-bitquantity).

• If both bounds are within the range 0..255, the variable is stored as a byte (unsigned 8-bitquantity).

• If both bounds are within the range -32768..32767, the variable is stored as a smallint (signed16-bit quantity).

• If both bounds are within the range 0..65535, the variable is stored as a word (unsigned 16-bitquantity)

• If both bounds are within the range 0..4294967295, the variable is stored as a longword (un-signed 32-bit quantity).

• Otherwise the variable is stored as a longint (signed 32-bit quantity).

char typesA char , or a subrange of the char type is stored as a byte.

boolean typesTheboolean type is stored as a byte and can take a value oftrue or false .

A ByteBool is stored as a byte, aWordBool type is stored as a word, and alongbool is storedas a longint.

enumeration typesBy default all enumerations are stored as a longword (4 bytes), which is equivalent to specifying the{$Z4} , {$PACKENUM 4}or {$PACKENUM DEFAULT}switches.

This default behavior can be changed by compiler switches, and by the compiler mode.

In the tp compiler mode, or while the{$Z1} or {$PACKENUM 1}switches are in effect, thestorage space used is shown in table (8.1).

When the{$Z2} or {$PACKENUM 2}switches are in effect, the value is stored on 2 bytes (word),if the enumeration has less or equal then 65535 elements, otherwise, the enumeration value is storedas a 4 byte value (longword).

70

Page 72: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

Table 8.1: Enumeration storage fortp mode

# Of Elements in Enum. Storage space used0..255 byte (1 byte)256..65535 word (2 bytes)> 65535 longword (4 bytes)

floating point typesFloating point type sizes and mapping vary from one processor to another. Except for the Intel80x86 architecture, theextended type maps to the IEEE double type if a hardware floating pointcoprocessor is present.

Table 8.2: Processor mapping of real type

Processor Real type mappingIntel 80x86 doubleMotorola 680x0 (with {$E-} switch) doubleMotorola 680x0 (with {$E+} switch) single

Floating point types have a storage binary format divided into three distinct fields : the mantissa, theexponent and the sign bit which stores the sign of the floating point value.

single

The single type occupies 4 bytes of storage space, and its memory structure is the same as theIEEE-754 single type. This type is the only type which is guaranteed to be available on all platforms(either emulated via software or directly via hardware).

The memory format of thesingle format looks like what is shown in figure (8.1).

Figure 8.1: The single format

71

Page 73: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

double

The double type occupies 8 bytes of storage space, and its memory structure is the same as theIEEE-754 double type.

The memory format of thedouble format looks like like what is shown in figure (8.2).

Figure 8.2: The double format

On processors which do not support co-processor operations (and which have the {$E+} switch), thedouble type does not exist.

extended

For Intel 80x86 processors, theextended type has takes up 10 bytes of memory space. For moreinformation on the extended type consult the Intel Programmer’s reference.

For all other processors which support floating point operations, theextended type is a nicknamefor the type which supports the most precision, this is usually thedouble type. On processorswhich do not support co-processor operations (and which have the {$E+} switch), theextendedtype usually maps to thesingle type.

comp

For Intel 80x86 processors, thecomp type contains a 63-bit integral value, and a sign bit (in the MSBposition). Thecomp type takes up 8 bytes of storage space.

On other processors, thecomp type is not supported.

real

Contrary to Turbo Pascal, where thereal type had a special internal format, under Free Pascal thereal type simply maps to one of the other real types. It maps to thedouble type on processorswhich support floating point operations, while it maps to thesingle type on processors which donot support floating point operations in hardware. See table (8.2) for more information on this.

pointer typesA pointer type is stored as a longword (unsigned 32-bit value) on 32-bit processors, and is storedas a 64-bit unsigned value1 on 64-bit processors.

1this is actually theqword type, which is not supported in Free Pascal v1.0

72

Page 74: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

string typesansistring types

The ansistring is a dynamically allocated string which has no length limitation. When the string isno longer being referenced (its reference count reaches zero), its memory is automatically freed.

If the ansistring is a constant, then its reference count will be equal to -1, indicating that it shouldnever be freed. The structure in memory for an ansistring is shown in table (8.3).

Table 8.3: AnsiString memory structure (32-bit model)

Offset Contains-12 Longint with maximum string size.-8 Longint with actual string size.-4 Longint with reference count.0 Actual array ofchar , null-terminated.

shortstring types

A shortstring occupies as many bytes as its maximum length plus one. The first byte contains thecurrent dynamic length of the string. The following bytes contain the actual characters (of typechar ) of the string. The maximum size of a short string is the length byte followed by 255 characters.

widestring types

The widestring (composed of unicode characters) is not supported in Free Pascal v1.0.

set typesA set is stored as an array of bits, where each bit indicates if the element is in the set or excludedfrom the set. The maximum number of elements in a set is 256.

If a set has less than 32 elements, it is coded as an unsigned 32-bit value. Otherwise it is coded as a8 element array of 32-bit unsigned values (longword) (hence a size of 256 bytes).

The longword number of a specific elementE is given by :

LongwordNumber = (E div 32);

and the bit number within that 32-bit value is given by:

BitNumber = (E mod 32);

array typesAn array is stored as a contiguous sequence of variables of the components of the array. The compon-ents with the lowest indexes are stored first in memory. No alignment is done between each elementof the array. A multi-dimensional array is stored with the rightmost dimension increasing first.

73

Page 75: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

record typesEach field of a record are stored in a contigous sequence of variables, where the first field is storedat the lowest address in memory. In case of variant fields in a record, each variant starts at the sameaddress in memory. Fields of record are usually aligned, unless thepacked directive is specifiedwhen declaring the record type. For more information on field alignment, consult section9, page77.

object typesObjects are stored in memory just as ordinary records with an extra field: a pointer to the VirtualMethod Table (VMT). This field is stored first, and all fields in the object are stored in the orderthey are declared (with possible alignment of field addresses, unless the object was declared as beingpacked ).

This field is initialized by the call to the object’sConstructor method. If thenew operator wasused to call the constructor, the data fields of the object will be stored in heap memory, otherwisethey will directly be stored in the data section of the final executable.

If an object doesn’t have virtual methods, no pointer to a VMT is inserted.

The memory allocated looks as in table (8.4).

Table 8.4: Object memory layout (32-bit model)

Offset What+0 Pointer to VMT (optional).+4 Data. All fields in the order they’ve been declared.. . .

The Virtual Method Table (VMT) for each object type consists of 2 check fields (containing the sizeof the data), a pointer to the object’s ancestor’s VMT (Nil if there is no ancestor), and then thepointers to all virtual methods. The VMT layout is illustrated in table (8.5). The VMT is constructedby the compiler.

Table 8.5: Object Virtual Method Table memory layout (32-bit model)

Offset What+0 Size of object type data+4 Minus the size of object type data. Enables determining of valid VMT pointers.+8 Pointer to ancestor VMT,Nil if no ancestor available.+12 Pointers to the virtual methods.. . .

class typesJust like objects, classes are stored in memory just as ordinary records with an extra field: a pointerto the Virtual Method Table (VMT). This field is stored first, and all fields in the class are stored inthe order they are declared.

Contrary to objects, all data fields of a class are always stored in heap memory.

The memory allocated looks as in table (8.6).

74

Page 76: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

Table 8.6: Class memory layout (32-bit model)

Offset What+0 Pointer to VMT.+4 Data. All fields in the order they’ve been declared.. . .

The Virtual Method Table (VMT) of each class consists of several fields, which are used for runtimetype information. The VMT layout is illustrated in table (8.7). The VMT is constructed by thecompiler.

Table 8.7: Class Virtual Method Table memory layout (32-bit model)

Offset What+0 Size of object type data+4 Minus the size of object type data. Enables determining of valid VMT pointers.+8 Pointer to ancestor VMT,Nil if no ancestor available.+12 Pointer to the class name (stored as ashortstring ).+16 Pointer to the dynamic method table (usingmessage with integers).+20 Pointer to the method definition table.+24 Pointer to the field definition table.+28 Pointer to type information table.+32 Pointer to instance initialization table.+36 Reserved.+40 Pointer to the interface table.+44 Pointer to the dynamic method table (usingmessage with strings).+48 Pointer to theDestroy destructor.+52 Pointer to theNewInstance method.+56 Pointer to theFreeInstance method.+60 Pointer to theSafeCallException method.+64 Pointer to theDefaultHandler method.+68 Pointer to theAfterConstruction method.+72 Pointer to theBeforeDestruction method.+76 Pointer to theDefaultHandlerStr method.+80 Pointers to other virtual methods.. . .

file typesFile types are represented as records. Typed files and untyped files are represented as a fixed record:

filerec = packed recordhandle : longint;mode : longint;recsize : longint;_private : array[1..32] of byte;userdata : array[1..16] of byte;name : array[0..255] of char;

End;

75

Page 77: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

Text files are described using the following record:

TextBuf = array[0..255] of char;textrec = packed record

handle : longint;mode : longint;bufsize : longint;_private : longint;bufpos : longint;bufend : longint;bufptr : ^textbuf;openfunc : pointer;inoutfunc : pointer;flushfunc : pointer;closefunc : pointer;userdata : array[1..16] of byte;name : array[0..255] of char;buffer : textbuf;

End;

handle The handle field returns the file handle (if the file is opened), as returned by the operatingsystem.

mode The mode field can take one of several values. When it isfmclosed , then the file is closed,and thehandle field is invalid. When the value is equal tofminput , it indicates that thefile is opened for read only access.fmoutput indicates write only access, and thefminoutindicates read-write access to the file.

name Thename field is a null terminated character string representing the name of the file.

userdata Theuserdata field is never used by Free Pascal, and can be used for special purposesby software developpers.

procedural typesA procedural type to a normal procedure or function is stored as a generic pointer, which stores theaddress of the entry point of the routine.

In the case of a method procedural type, the storage consists of two pointers, the first being a pointerto the entry point of the method, and the second one being a pointer toself (the object instance).

8.3 Data alignment

Typed constants and variable alignmentAll static data (variables and typed constants) which are greater than a byte are usually aligned ona power of two boundary. This alignment applies only to the start address of the variables, and notthe alignment of fields within structures or objects for example. For more information on structuredalignment, section9, page77. The alignment is similar across the different target processors.2

The alignment columns indicates the address alignment of the variable, i.e the start address of thevariable will be aligned on that boundary. The small size alignment is valid when the code generated

2The Intel 80x86 version does not align data in the case of constant strings, constant sets, constant floating point valuesamd global variables. This will be fixed in the version 1.1 release.

76

Page 78: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

Table 8.8: Data alignment

Data size (bytes) Alignment (small size) Alignment (fast)1 1 12-3 2 24-7 2 48+ 2 4

should be optimized for size (-Og compiler option) and not speed, otherwise and by default, the fastalignment is used to align the data.

Structured types alignmentBy default all elements in a structure are aligned to a 2 byte boundary, unless the$PACKRECORDSdirective orpacked modifier is used to align the data in another way. For example arecord orobject having a 1 byte element, will have its size rounded up to 2, so the size of the structure willactually be 2 bytes.

8.4 The heap

The heap is used to store all dynamic variables, and to store class instances. The interface to theheap is the same as in Turbo Pascal, although the effects are maybe not the same. On top of that, theFree Pascal run-time library has some extra possibilities, not available in Turbo Pascal. These extrapossibilities are explained in the next subsections.

Heap allocation strategyThe heap is a memory structure which is organized as a stack. The heap bottom is stored in thevariableHeapOrg . Initially the heap pointer (HeapPtr ) points to the bottom of the heap. Whena variable is allocated on the heap,HeapPtr is incremented by the size of the allocated memoryblock. This has the effect of stacking dynamic variables on top of each other.

Each time a block is allocated, its size is normalized to have a granularity of 16 bytes.

WhenDispose or FreeMem is called to dispose of a memory block which is not on the top ofthe heap, the heap becomes fragmented. The deallocation routines also add the freed blocks to thefreelist which is actually a linked list of free blocks. Furthermore, if the deallocated block wasless then 8K in size, the free list cache is also updated.

The free list cache is actually a cache of free heap blocks which have specific lengths (the adjustedblock size divided by 16 gives the index into the free list cache table). It is faster to access thensearching through the entirefreelist .

The format of an entry in thefreelist is as follows:

PFreeRecord = ^TFreeRecord;TFreeRecord = record

Size : longint;Next : PFreeRecord;Prev : PFreeRecord;

end;

77

Page 79: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

TheNext field points to the next free block, while thePrev field points to the previous free block.

The algorithm for allocating memory is as follows:

1. The size of the block to allocate is adjusted to a 16 byte granularity.

2. The cached free list is searched to find a free block of the specified size or bigger size, if so itis allocated and the routine exits.

3. The freelist is searched to find a free block of the specified size or of bigger size, if so itis allocated and the routine exits.

4. If not found in thefreelist the heap is grown to allocate the specified memory, and theroutine exits.

5. If the heap cannot be grown internally anymore and ifheaperror is set accordingly, it callsthe heap error handler. If there is no heap error handler installed, the runtime library generatesa runtime error 203.

The HeapError variableThe heap error permits developpers to install a heap error hook which is called each time an allocationcannot be completed by the default heap manager.HeapError is a pointer that points to a functionwith the following prototype:

function HeapFunc(size : longint): integer;

The size parameter indicates the size of the block which could not be allocated. Depending onthe success, the error handler routine should return a value which indicates what the default heapmanager should do thereafter (cf. table (8.9)).

Table 8.9: Heap error result

Value returned Memory manager action0 Generates a runtime error 2031 GetMem,ReallocMem andNewreturnsnil2 Try allocating the memory block once again

The heap growsBy default,HeapError points to theGrowHeap function, which tries to increase the heap.

TheGrowHeap function issues a system call to try to increase the size of the memory available toyour program. It first tries to increase memory in a 256Kb chunk if the size to allocate is less than256Kb, or 1024K otherwise. If this fails, it tries to increase the heap by the amount you requestedfrom the heap.

If the call toGrowHeap was successful, then the needed memory will be allocated.

If the call toGrowHeap fails, the value returned depends on the value of theReturnNilIfGrowHeapFailsglobal variable. This is summarized in table (8.10).

ReturnNilIfGrowHeapFails can be set to change the behavior of the default memory managererror handler.

78

Page 80: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

Table 8.10: ReturnNilIfGrowHeapFails value

ReturnNilGrowHeapFails Default memoryvalue manager action

FALSE (The default) Runtime error 203 generatedTRUE GetMem, ReallocMem andNewreturnsnil

Debugging the heapFree Pascal provides a unit that allows you to trace allocation and deallocation of heap memory:heaptrc.

If you specify the-gh switch on the command-line, or if you includeheaptrc as the first unit inyour uses clause, the memory manager will trace what is allocated and deallocated, and on exit ofyour program, a summary will be sent to standard output.

More information on using theheaptrc mechanism can be found in theUsers guideand Unitreference.

Writing your own memory managerFree Pascal allows you to write and use your own memory manager. The standard functionsGetMem,FreeMem, ReallocMem andMaxavail use a special record in thesystem unit to do the actualmemory management. Thesystem unit initializes this record with thesystem unit’s own memorymanager, but you can read and set this record using theGetMemoryManager andSetMemoryManagercalls:

procedure GetMemoryManager(var MemMgr: TMemoryManager);procedure SetMemoryManager(const MemMgr: TMemoryManager);

theTMemoryManager record is defined as follows:

TMemoryManager = recordGetmem : Function(Size:Longint):Pointer;Freemem : Function(var p:pointer):Longint;FreememSize : Function(var p:pointer;Size:Longint):Longint;AllocMem : Function(Size:longint):Pointer;ReAllocMem : Function(var p:pointer;Size:longint):Pointer;MemSize : function(p:pointer):Longint;MemAvail : Function:Longint;MaxAvail : Function:Longint;HeapSize : Function:Longint;

end;

As you can see, the elements of this record are procedural variables. Thesystem unit does nothingbut call these various variables when you allocate or deallocate memory.

Each of these functions corresponds to the corresponding call in thesystem unit. We’ll describeeach one of them:

Getmem This function allocates a new block on the heap. The block should beSize bytes long.The return value is a pointer to the newly allocated block.

Freemem should release a previously allocated block. The pointerP points to a previously allocatedblock. The Memory manager should implement a mechanism to determine what the size of

79

Page 81: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

the memory block is3 The return value is optional, and can be used to return the size of thefreed memory.

FreememSizeThis function should release the memory pointed to byP. The argumentSize is theexpected size of the memory block pointed to by P. This should be disregarded, but can be usedto check the behaviour of the program.

AllocMem Is the same as getmem, only the allocated memory should be filled with zeroes beforethe call returns.

ReAllocMem Should allocate a memory blockSize bytes large, and should fill it with the contentsof the memory block pointed to byP, truncating this to the new size of needed. After that, thememory pointed to by P may be deallocated. The return value is a pointer to the new memoryblock. Note thatP may beNil , in which case the behaviour is equivalent toGetMem.

MemSize should return the total amount of memory available for allocation. This function mayreturn zero if the memory manager does not allow to determine this information.

MaxAvail should return the size of the largest block of memory that is still available for alloca-tion. This function may return zero if the memory manager does not allow to determine thisinformation.

HeapSize should return the total size of the heap. This may be zero is the memory manager doesnot allow to determine this information.

To implement your own memory manager, it is sufficient to construct such a record and to issue acall toSetMemoryManager .

To avoid conflicts with the system memory manager, setting the memory manager should happen assoon as possible in the initialization of your program, i.e. before any call togetmem is processed.

This means in practice that the unit implementing the memory manager should be the first in theuses clause of your program or library, since it will then be initialized before all other units (exceptof thesystem unit)

This also means that it is not possible to use theheaptrc unit in combination with a custom memorymanager, since theheaptrc unit uses the system memory manager to do all it’s allocation. Putting theheaptrc unit after the unit implementing the memory manager would overwrite the memory managerrecord installed by the custom memory manager, and vice versa.

The following unit shows a straightforward implementation of a custom memory manager using thememory manager of theC library. It is distributed as a package with Free Pascal.

unit cmem;

{$mode objfpc}

interface

Function Malloc (Size : Longint) : Pointer;cdecl;external ’c’ name ’malloc’;

Procedure Free (P : pointer); cdecl; external ’c’ name ’free’;Procedure FreeMem (P : Pointer); cdecl; external ’c’ name ’free’;function ReAlloc (P : Pointer; Size : longint) : pointer; cdecl;

external ’c’ name ’realloc’;Function CAlloc (unitSize,UnitCount : Longint) : pointer;cdecl;

external ’c’ name ’calloc’;

3By storing it’s size at a negative offset for instance.

80

Page 82: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

implementation

Function CGetMem (Size : Longint) : Pointer;

beginresult:=Malloc(Size);

end;

Function CFreeMem (Var P : pointer) : Longint;

beginFree(P);Result:=0;

end;

Function CFreeMemSize(var p:pointer;Size:Longint):Longint;

beginResult:=CFreeMem(P);

end;

Function CAllocMem(Size : Longint) : Pointer;

beginResult:=calloc(Size,1);

end;

Function CReAllocMem (var p:pointer;Size:longint):Pointer;

beginResult:=realloc(p,size);

end;

Function CMemSize (p:pointer): Longint;

beginResult:=0;

end;

Function CMemAvail : Longint;

beginResult:=0;

end;

Function CMaxAvail: Longint;

beginResult:=0;

end;

Function CHeapSize : Longint;

81

Page 83: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

beginResult:=0;

end;

ConstCMemoryManager : TMemoryManager =

(GetMem : CGetmem;FreeMem : CFreeMem;FreememSize : CFreememSize;AllocMem : CAllocMem;ReallocMem : CReAllocMem;MemSize : CMemSize;MemAvail : CMemAvail;MaxAvail : MaxAvail;HeapSize : CHeapSize;

);

VarOldMemoryManager : TMemoryManager;

InitializationGetMemoryManager (OldMemoryManager);SetMemoryManager (CmemoryManager);

FinalizationSetMemoryManager (OldMemoryManager);

end.

8.5 UsingDOS memory under the Go32 extender

Because Free Pascal forDOS is a 32 bit compiler, and uses aDOS extender, accessing DOS memoryisn’t trivial. What follows is an attempt to an explanation of how to access and useDOS or real modememory4.

In Proteced Mode, memory is accessed throughSelectorsandOffsets. You can think of Selectors asthe protected mode equivalents of segments.

In Free Pascal, a pointer is an offset into theDSselector, which points to the Data of your program.

To access the (real mode)DOSmemory, somehow you need a selector that points to theDOSmemory.Thego32 unit provides you with such a selector: TheDosMemSelector variable, as it is conveni-ently called.

You can also allocate memory inDOS’s memory space, using theglobal_dos_alloc functionof thego32 unit. This function will allocate memory in a place whereDOS sees it.

As an example, here is a function that returns memory in real modeDOS and returns a selector:offsetpair for it.

procedure dosalloc(var selector : word;var segment : word;size : longint);

4Thanks for the explanation to Thomas Schatzl (E-mail:[email protected] )

82

Page 84: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 8. MEMORY ISSUES

var result : longint;

beginresult := global_dos_alloc(size);selector := word(result);segment := word(result shr 16);

end;

(You need to free this memory using theglobal_dos_free function.)

You can access any place in memory using a selector. You can get a selector using theallocate_ldt_descriptorfunction, and then let this selector point to the physical memory you want using theset_segment_base_addressfunction, and set its length usingset_segment_limit function. You can manipulate the memorypointed to by the selector using the functions of the GO32 unit. For instance with theseg_fillcharfunction. After using the selector, you must free it again using thefree_ldt_selector function.

More information on all this can be found in theUnit reference, the chapter on thego32 unit.

83

Page 85: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 9

Resource strings

9.1 Introduction

Resource strings primarily exist to make internationalization of applications easier, by introducing alanguage construct that provides a uniform way of handling constant strings.

Most applications communicate with the user through some messages on the graphical screen orconsole. Storing these messages in special constants allows to store them in a uniform way in separatefiles, which can be used for translation. A programmers interface exists to manipulate the actualvalues of the constant strings at runtime, and a utility tool comes with the Free Pascal compiler toconvert the resource string files to whatever format is wanted by the programmer. Both these thingsare discussed in the following sections.

9.2 The resource string file

When a unit is compiled that contains aresourcestring section, the compiler does 2 things:

1. It generates a table that contains the value of the strings as it is declared in the sources.

2. It generates aresource string filethat contains the names of all strings, together with theirdeclared values.

This approach has 2 advantages: first of all, the value of the string is always present in the pro-gram. If the programmer doesn’t care to translate the strings, the default values are always presentin the binary. This also avoids having to provide a file containing the strings. Secondly, having allstrings together in a compiler generated file ensures that all strings are together (you can have mul-tiple resourcestring sections in 1 unit or program) and having this file in a fixed format, allows theprogrammer to choose his way of internationalization.

For each unit that is compiled and that contains a resourcestring section, the compiler generates a filethat has the name of the unit, and an extension.rst. The format of this file is as follows:

1. An empty line.

2. A line starting with a hash sign (#) and the hash value of the string, preceded by the texthashvalue = .

3. A third line, containing the name of the resource string in the formatunitname.constantname ,all lowercase, followed by an equal sign, and the string value, in a format equal to the pascal

84

Page 86: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 9. RESOURCE STRINGS

representation of this string. The line may be continued on the next line, in that case it readsas a pascal string expression with a plus sign in it.

4. Another empty line.

If the unit contains noresourcestring section, no file is generated.

For example, the following unit:

unit rsdemo;

{$mode delphi}{$H+}

interface

resourcestring

First = ’First’;Second = ’A Second very long string that should cover more than 1 line’;

implementation

end.

Will result in the following resource string file:

# hash value = 5048740rsdemo.first=’First’

# hash value = 171989989rsdemo.second=’A Second very long string that should cover more than 1 li’+’ne’

The hash value is calculated with the functionHash. It is present in theobjpas unit. The value isthe same value that the GNU gettext mechanism uses. It is in no way unique, and can only be usedto speed up searches.

The rstconv utility that comes with the Free Pascal compiler allows to manipulate these resourcestring files. At the moment, it can only be used to make a.po file that can be fed to the GNUmsgfmtprogram. If someone wishes to have another format (Win32 resource files spring to mind), one canenhance therstconv program so it can generate other types of files as well. GNU gettext was chosenbecause it is available on all platforms, and is already widely used in theUnix and free softwarecommunity. Since the Free Pascal team doesn’t want to restrict the use of resource strings, the.rstformat was chosen to provide a neutral method, not restricted to any tool.

If you use resource strings in your units, and you want people to be able to translate the strings, youmust provide the resource string file. Currently, there is no way to extract them from the unit file,though this is in principle possible. It is not required to do this, the program can be compiled withoutit, but then the translation of the strings isn’t possible.

85

Page 87: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 9. RESOURCE STRINGS

9.3 Updating the string tables

Having compiled a program with resourcestrings is not enough to internationalize your program. Atrun-time, the program must initialize the string tables with the correct values for the anguage thatthe user selected. By default no such initialization is performed. All strings are initialized with theirdeclared values.

The objpas unit provides the mechanism to correctly initialize the string tables. There is no needto include this unit in auses clause, since it is automatically loaded when a program or unit iscompiled inDelphi or objfpc mode. Since this is required to use resource strings, the unit isalways loaded when needed.

The resource strings are stored in tables, one per unit, and one for the program, if it contains aresourcestring section as well. Each resourcestring is stored with it’s name, hash value, defaultvalue, and the current value, all asAnsiStrings .

The objpas unit offers methods to retrieve the number of resourcestring tables, the number of stringsper table, and the above information for each string. It also offers a method to set the current valueof the strings.

Here are the declarations of all the functions:

Function ResourceStringTableCount : Longint;Function ResourceStringCount(TableIndex : longint) : longint;Function GetResourceStringName(TableIndex,

StringIndex : Longint) : Ansistring;Function GetResourceStringHash(TableIndex,

StringIndex : Longint) : Longint;Function GetResourceStringDefaultValue(TableIndex,

StringIndex : Longint) : AnsiString;Function GetResourceStringCurrentValue(TableIndex,

StringIndex : Longint) : AnsiString;Function SetResourceStringValue(TableIndex,

StringIndex : longint;Value : Ansistring) : Boolean;

Procedure SetResourceStrings (SetFunction : TResourceIterator);

Two other function exist, for convenience only:

Function Hash(S : AnsiString) : longint;Procedure ResetResourceTables;

Here is a short explanation of what each function does. A more detailed explanation of the functionscan be found in theReference guide.

ResourceStringTableCount returns the number of resource string tables in the program.

ResourceStringCount returns the number of resource string entries in a given table (tables are de-noted by a zero-based index).

GetResourceStringNamereturns the name of a resource string in a resource table. This is thename of the unit, a dot (.) and the name of the string constant, all in lowercase. The strings aredenoted by index, also zero-based.

GetResourceStringHashreturns the hash value of a resource string, as calculated by the compilerwith theHash function.

GetResourceStringDefaultValue returns the default value of a resource string, i.e. the value thatappears in the resource string declaration, and that is stored in the binary.

86

Page 88: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 9. RESOURCE STRINGS

GetResourceStringCurrentValue returns the current value of a resource string, i.e. the value setby the initialization (the default value), or the value set by some previous internationalizationroutine.

SetResourceStringValuesets the current value of a resource string. This function must be called toinitialize all strings.

SetResourceStringsgiving this function a callback will cause the calback to be called for all re-source strings, one by one, and set the value of the string to the return value of the callback.

Two other functions exist, for convenience only:

Hash can be used to calculate the hash value of a string. The hash value stored in the tables is theresult of this function, applied on the default value. That value is calculated at compile timeby the compiler.

ResetResourceTableswill reset all the resource strings to their default values. It is called by theinitialization code of the objpas unit.

Given someTranslate function, the following code would initialize all resource strings:

Var I,J : Longint;S : AnsiString;

beginFor I:=0 to ResourceStringTableCount-1 do

For J:=0 to ResourceStringCount(i)-1 dobeginS:=Translate(GetResourceStringDefaultValue(I,J));SetResourceStringValue(I,J,S);end;

end;

Other methods are of course possible, and theTranslate function can be implemented in a varietyof ways.

9.4 GNU gettext

The unitgettext provides a way to internationalize an application with the GNUgettext utilities.This unit is supplied with the Free Component Library (FCL). it can be used as follows:

for a given application, the following steps must be followed:

1. Collect all resource string files and concatenate them together.

2. Invoke therstconv program with the file resulting out of step 1, resulting in a single.po filecontaining all resource strings of the program.

3. Translate the.po file of step 2 in all required languages.

4. Run themsgfmt formatting program on all the.po files, resulting in a set of.mo files, whichcan be distributed with your application.

5. Call thegettext unit’s TranslateReosurceStrings method, giving it a template for thelocation of the.mo files, e.g. as in

87

Page 89: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 9. RESOURCE STRINGS

TranslateResourcestrings(’intl/restest.%s.mo’);

the%sspecifier will be replaced by the contents of theLANGenvironment variable. This callshould happen at program startup.

An example program exists in the FCL sources, in thefcl/tests directory.

9.5 Caveat

In principle it is possible to translate all resource strings at any time in a running program. However,this change is not communicated to other strings; its change is noticed only when a constant string isbeing used.

Consider the following example:

Consthelp = ’With a little help of a programmer.’;

VarA : AnsiString;

begin

{ lots of code }

A:=Help;

{ Again some code}

TranslateStrings;

{ More code }

After the call toTranslateStrings , the value ofA will remain unchanged. This means that theassignmentA:=Help must be executed again in order for the change to become visible. This isimportant, especially for GUI programs which have e.g. a menu. In order for the change in resourcestrings to become visible, the new values must be reloaded by program code into the menus . . .

88

Page 90: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 10

Optimizations

10.1 Non processor specific

The following sections describe the general optimizations done by the compiler, they are not pro-cessor specific. Some of these require some compiler switch override while others are done automat-ically (those which require a switch will be noted as such).

Constant foldingIn Free Pascal, if the operand(s) of an operator are constants, they will be evaluated at compile time.

Example

x:=1+2+3+6+5;

will generate the same code as

x:=17;

Furthermore, if an array index is a constant, the offset will be evaluated at compile time. This meansthat accessing MyData[5] is as efficient as accessing a normal variable.

Finally, callingChr , Hi , Lo , Ord , Pred , or Succ functions with constant parameters generates norun-time library calls, instead, the values are evaluated at compile time.

Constant mergingUsing the same constant string, floating point value or constant set two or more times generates onlyone copy of that constant.

Short cut evaluationEvaluation of boolean expression stops as soon as the result is known, which makes code executefaster then if all boolean operands were evaluated.

Constant set inliningUsing thein operator is always more efficient then using the equivalent<>, =, <=, >=, < and>operators. This is because range comparisons can be done more easily within then with normal

89

Page 91: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 10. OPTIMIZATIONS

comparison operators.

Small setsSets which contain less then 33 elements can be directly encoded using a 32-bit value, therefore norun-time library calls to evaluate operands on these sets are required; they are directly encoded bythe code generator.

Range checkingAssignments of constants to variables are range checked at compile time, which removes the need ofthe generation of runtime range checking code.

And instead of moduloWhen the second operand of amodon an unsigned value is a constant power of 2, anand instructionis used instead of an integer division. This generates more efficient code.

Shifts instead of multiply or divideWhen one of the operands in a multiplication is a power of two, they are encoded using arithmeticshift instructions, which generates more efficient code.

Similarly, if the divisor in adiv operation is a power of two, it is encoded using arithmetic shiftinstructions.

The same is true when accessing array indexes which are powers of two, the address is calculatedusing arithmetic shifts instead of the multiply instruction.

Automatic alignmentBy default all variables larger then a byte are guaranteed to be aligned at least on a word boundary.

Alignment on the stack and in the data section is processor dependant.

Smart linkingThis feature removes all unreferenced code in the final executable file, making the executable filemuch smaller.

Smart linking is switched on with the-Cx command-line switch, or using the{$SMARTLINK ON}global directive.

Inline routinesThe following runtime library routines are coded directly into the final executable:Lo , Hi , High ,Sizeof , TypeOf , Length , Pred , Succ , Inc , Dec andAssigned .

Stack frame omissionUnder specific conditions, the stack frame (entry and exit code for the routine, see section section6.3, page55) will be omitted, and the variable will directly be accessed via the stack pointer.

90

Page 92: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 10. OPTIMIZATIONS

Conditions for omission of the stack frame:

• The function has no parameters nor local variables.

• Routine is declared with theassembler modifier.

• Routine is not a class.

Register variablesWhen using the-Or switch, local variables or parameters which are used very often will be movedto registers for faster access.

10.2 Processor specific

This lists the low-level optimizations performed, on a processor per processor basis.

Intel 80x86 specificHere follows a listing of the optimizing techniques used in the compiler:

1. When optimizing for a specific Processor (-Op1, -Op2, -Op3 , the following is done:

• In case statements, a check is done whether a jump table or a sequence of conditionaljumps should be used for optimal performance.

• Determines a number of strategies when doing peephole optimization, e.g.:movzbl(%ebp), %eax will be changed intoxorl %eax,%eax; movb (%ebp),%alfor Pentium and PentiumMMX.

2. When optimizing for speed (-OG, the default) or size (-Og ), a choice is made between usingshorter instructions (for size) such asenter $4 , or longer instructionssubl $4,%esp forspeed. When smaller size is requested, data is aligned to minimal boundaries. When speed isrequested, data is aligned on most efficient boundaries as much as possible.

3. Fast optimizations (-O1 ): activate the peephole optimizer

4. Slower optimizations (-O2 ): also activate the common subexpression elimination (formerlycalled the "reloading optimizer")

5. Uncertain optimizations (-Ou ): With this switch, the common subexpression elimination al-gorithm can be forced into making uncertain optimizations.

Although you can enable uncertain optimizations in most cases, for people who do not under-stand the following technical explanation, it might be the safest to leave them off.

Remark: If uncertain optimizations are enabled, the CSE algortihm assumes that

• If something is written to a local/global register or a procedure/function parameter, thisvalue doesn’t overwrite the value to which a pointer points.

• If something is written to memory pointed to by a pointer variable, this value doesn’toverwrite the value of a local/global variable or a procedure/function parameter.

The practical upshot of this is that you cannot use the uncertain optimizations if you both writeand read local or global variables directly and through pointers (this includesVar parameters,as those are pointers too).

The following example will produce bad code when you switch on uncertain optimizations:

91

Page 93: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 10. OPTIMIZATIONS

Var temp: Longint;

Procedure Foo(Var Bar: Longint);Begin

If (Bar = temp)Then

BeginInc(Bar);If (Bar <> temp) then Writeln(’bug!’)

EndEnd;

BeginFoo(Temp);

End.

The reason it produces bad code is because you access the global variableTempboth throughits nameTempand through a pointer, in this case using theBar variable parameter, which isnothing but a pointer toTemp in the above code.

On the other hand, you can use the uncertain optimizations if you access global/local variablesor parameters through pointers, andonlyaccess them through this pointer1.

For example:

Type TMyRec = Recorda, b: Longint;

End;PMyRec = ^TMyRec;

TMyRecArray = Array [1..100000] of TMyRec;PMyRecArray = ^TMyRecArray;

Var MyRecArrayPtr: PMyRecArray;MyRecPtr: PMyRec;Counter: Longint;

BeginNew(MyRecArrayPtr);For Counter := 1 to 100000 Do

BeginMyRecPtr := @MyRecArrayPtr^[Counter];MyRecPtr^.a := Counter;MyRecPtr^.b := Counter div 2;

End;End.

Will produce correct code, because the global variableMyRecArrayPtr is not accesseddirectly, but only through a pointer (MyRecPtr in this case).

In conclusion, one could say that you can use uncertain optimizationsonly when you knowwhat you’re doing.

1 You can use multiple pointers to point to the same variable as well, that doesn’t matter.

92

Page 94: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 10. OPTIMIZATIONS

Motorola 680x0 specificUsing the-O2 (the default) switch does several optimizations in the code produced, the most notablebeing:

• Sign extension from byte to long will useEXTB

• Returning of functions will useRTD

• Range checking will generate no run-time calls

• Multiplication will use the longMULSinstruction, no runtime library call will be generated

• Division will use the longDIVS instruction, no runtime library call will be generated

10.3 Optimization switches

This is where the various optimizing switches and their actions are described, grouped per switch.

-On: with n = 1..3: these switches activate the optimizer. A higher level automatically includes alllower levels.

• Level 1 (-O1 ) activates the peephole optimizer (common instruction sequences are re-placed by faster equivalents).

• Level 2 (-O2 ) enables the assembler data flow analyzer, which allows the common subex-pression elimination procedure to remove unnecessary reloads of registers with valuesthey already contain.

• Level 3 (-O3 ) enables uncertain optimizations. For more info, see -Ou.

-OG: This causes the code generator (and optimizer, IF activated), to favor faster, but code-wise lar-ger, instruction sequences (such as "subl $4,%esp ") instead of slower, smaller instructions("enter $4 "). This is the default setting.

-Og: This one is exactly the reverse of -OG, and as such these switches are mutually exclusive:enabling one will disable the other.

-Or: This setting causes the code generator to check which variables are used most, so it can keepthose in a register.

-Opn: with n = 1..3: Setting the target processor does NOT activate the optimizer. It merely influ-ences the code generator and, if activated, the optimizer:

• During the code generation process, this setting is used to decide whether a jump tableor a sequence of successive jumps provides the best performance in a case statement.

• The peephole optimizer takes a number of decisions based on this setting, for example ittranslates certain complex instructions, such as

movzbl (mem), %eax|

to a combination of simpler instructions

xorl %eax, %eaxmovb (mem), %al

for the Pentium.

-Ou: This enables uncertain optimizations. You cannot use these always, however. The previoussection explains when they can be used, and when they cannot be used.

93

Page 95: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 10. OPTIMIZATIONS

10.4 Tips to get faster code

Here, some general tips for getting better code are presented. They mainly concern coding style.

• Find a better algorithm. No matter how much you and the compiler tweak the code, a quicksortwill (almost) always outperform a bubble sort, for example.

• Use variables of the native size of the processor you’re writing for. This is currently 32-bit or64-bit for Free Pascal, so you are best to use longword and longint variables.

• Turn on the optimizer.

• Write your if/then/else statements so that the code in the "then"-part gets executed most of thetime (improves the rate of successful jump prediction).

• Do not use ansistrings, widestrings and exception support, as these require a lot of code over-head.

• Profile your code (see the -pg switch) to find out where the bottlenecks are. If you want,you can rewrite those parts in assembler. You can take the code generated by the compileras a starting point. When given the-a command-line switch, the compiler will not erase theassembler file at the end of the assembly process, so you can study the assembler file.

10.5 Tips to get smaller code

Here are some tips given to get the smallest code possible.

• Find a better algorithm.

• Use the-Og compiler switch.

• Regroup global static variables in the same module which have the same size together to min-imize the number of alignment directives (which increases the.bss and .data sectionsunecessarily). Internally this is due to the fact that all static data is written to in the assemblerfile, in the order they are declared in the pascal source code.

• Do not use thecdecl modifier, as this generates about 1 additional instruction after eachsubroutine call.

• Use the smartlinking options for all your units (including thesystem unit).

• Do not use ansistrings, widestrings and exception support, as these require a lot of code over-head.

• Turn off range checking and stack-checking.

• Turn off runtime type information generation

94

Page 96: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 11

Programming shared libraries

11.1 Introduction

Free Pascal supports the creation of shared libraries on several operating systems. The followingtable (table (11.1)) indicates which operating systems support the creation of shared libraries.

Table 11.1: Shared library support

Operating systems Library extension Library prefixlinux .so libwindows .dll <none>BeOS .so libFreeBSD .so libNetBSD .so lib

The library prefix column indicates how the names of the libraries are resolved and created. Forexample, underLINUX , the library name will alwaus have thelib prefix when it is created. So ifyou create a library calledmylib, underLINUX , this will result in thelibmylib.so. Furthermore, whenimporting routines from shared libraries, it is not necessary to give the library prefix or the filenameextension.

In the following sections we discuss how to create a library, and how to use these libraries in pro-grams.

11.2 Creating a library

Creation of libraries is supported in any mode of the Free Pascal compiler, but it may be that thearguments or return values differ if the library is compiled in 2 different modes. E.g. if your functionexpects anInteger argument, then the library will expect different integer sizes if you compile itin Delphi mode or in TP mode.

A library can be created just as a program, only it uses thelibrary keyword, and it has anexports section. The following listing demonstrates a simple library:

Listing: progex/subs.pp

{Example l i b r a r y

95

Page 97: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 11. PROGRAMMING SHARED LIBRARIES

}l i b r a r y subs ;

funct ion SubStr ( CStr ing : PChar ; FromPos , ToPos : Longin t ) : PChar ;cdecl ; export ;

varLength : I n t ege r ;

beginLength : = StrLen ( CStr ing ) ;SubStr : = CStr ing + Length ;i f ( FromPos > 0 ) and ( ToPos >= FromPos ) thenbegin

i f Length >= FromPos thenSubStr : = CStr ing + FromPos − 1;

i f Length > ToPos thenCStr ing [ ToPos ] : = # 0 ;

end ;end ;

exportsSubStr ;

end .

The functionSubStr does not have to be declared in the library file itself. It can also be declared inthe interface section of a unit that is used by the library.

Compilation of this source will result in the creation of a library calledlibsubs.so on UNIX systems,or subs.dll on WINDOWS or OS/2. The compiler will take care of any additional linking that isrequired to create a shared library.

The library exports one function:SubStr . The case is important. The case as it appears in theexports clause is used to export the function.

If you want your library to be called from programs compiled with other compilers, it is importantto specify the correct calling convention for the exported functions. Since the generated programsby other compilers do not know about the Free Pascal calling conventions, your functions would becalled incorrectly, resulting in a corrupted stack.

On WINDOWS, most libraries use thestdcall convention, so it may be better to use that one ifyour library is to be used on WINDOWS systems. On mostUNIX systems, the C calling conventionis used, therefore thecdecl modifier should be used in that case.

11.3 Using a library in a pascal program

In order to use a function that resides in a library, it is sufficient to declare the function as it exists inthe library as anexternal function, with correct arguments and return type. The calling conventionused by the function should be declared correctly as well. The compiler will then link the library asspecified in theexternal statement to your program1.

For example, to use the library as defined above from a pascal program, you can use the followingpascal program:

Listing: progex/psubs.pp

1If you omit the library name in theexternal modifier, then you can still tell the compiler to link to that library usingthe{$Linklib} directive.

96

Page 98: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 11. PROGRAMMING SHARED LIBRARIES

program tes tsubs ;

funct ion SubStr ( const CStr ing : PChar ; FromPos , ToPos : l o n g i n t ) : PChar ;cdecl ; external ’ subs ’ ;

vars : PChar ;FromPos , ToPos : I n tege r ;

begins : = ’ Test ’ ;FromPos : = 2 ;ToPos : = 3 ;WriteLn ( SubStr ( s , FromPos , ToPos ) ) ;

end .

As is shown in the example, you must declare the function asexternal . Here also, it is necessaryto specify the correct calling convention (it should always match the convention as used by thefunction in the library), and to use the correct casing for your declaration. Also notice, that thelibrary importing did not specify the filename extension, nor was thelib prefix added.

This program can be compiled without any additional command-switches, and should run just likethat, provided the library is placed where the system can find it. For example, onLINUX , this is/usr/lib or any directory listed in the/etc/ld.so.conf file. On WINDOWS, this can be the programdirectory, the WINDOWS system directory, or any directoy mentioned in thePATH.

Using the library in this way links the library to your program at compile time. This means that

1. The library must be present on the system where the program is compiled.

2. The library must be present on the system where the program is executed.

3. Both libraries must be exactly the same.

Or it may simply be that you don’t know the name of the function to be called, you just know thearguments it expects.

It is therefore also possible to load the library at run-time, store the function address in a proceduralvariable, and use this procedural variable to access the function in the library.

The following example demonstrates this technique:

Listing: progex/plsubs.pp

program tes tsubs ;

TypeTSubStrFunc =

funct ion ( const CStr ing : PChar ; FromPos , ToPos : l o n g i n t ) : PChar ; cdecl ;

Function dlopen (name : pchar ; mode : l o n g i n t ) : p o i n t e r ; cdecl ; external ’ d l ’ ;Function dlsym ( l i b : p o i n t e r ; name : pchar ) : p o i n t e r ; cdecl ; external ’ d l ’ ;Function d l c l ose ( l i b : p o i n t e r ) : l o n g i n t ; cdecl ; external ’ d l ’ ;

vars : PChar ;FromPos , ToPos : I n tege r ;l i b : p o i n t e r ;SubStr : TSubStrFunc ;

begin

97

Page 99: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 11. PROGRAMMING SHARED LIBRARIES

s : = ’ Test ’ ;FromPos : = 2 ;ToPos : = 3 ;l i b := dlopen ( ’ l i b subs . so ’ , 1 ) ;Po in te r ( Substr ) : = dlsym ( l i b , ’ SubStr ’ ) ;WriteLn ( SubStr ( s , FromPos , ToPos ) ) ;d l c l ose ( l i b ) ;

end .

As in the case of compile-time linking, the crucial thing in this listing is the declaration of theTSubStrFunc type. It should match the declaration of the function you’re trying to use. Failureto specify a correct definition will result in a faulty stack or, worse still, may cause your program tocrash with an access violation.

11.4 Using a pascal library from a C program

Remark: The examples in this section assume aLINUX system; similar commands as the ones below exist forother operating systems, though.

You can also call a Free Pascal generated library from a C program:

Listing: progex/ctest.c

#include < s t r i n g . h>

extern char ∗ SubStr ( const char ∗ , in t , i n t ) ;

i n t main ( ){

char ∗ s ;i n t FromPos , ToPos ;

s = st rdup ( " Test " ) ;FromPos = 2 ;ToPos = 3 ;p r i n t f ( " Resul t from SubStr : ’% s ’ \ n " , SubStr ( s , FromPos , ToPos ) ) ;return 0 ;

}

To compile this example, the following command can be used:

gcc -o ctest ctest.c -lsubs

provided the code is inctest.c.

The library can also be loaded dynamically from C, as shown in the following example:

Listing: progex/ctest2.c

#include < d l f c n . h>#include < s t r i n g . h>

i n t main ( ){

void ∗ l i b ;char ∗ s ;i n t FromPos , ToPos ;char ∗ (∗ SubStr ) ( const char ∗ , in t , i n t ) ;

98

Page 100: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 11. PROGRAMMING SHARED LIBRARIES

l i b = dlopen ( " . / l i b subs . so " , RTLD_LAZY ) ;SubStr = dlsym ( l i b , "SUBSTR" ) ;

s = s t rdup ( " Test " ) ;FromPos = 2 ;ToPos = 3 ;p r i n t f ( " Resul t from SubStr : ’% s ’ \ n " , ( ∗ SubStr ) ( s , FromPos , ToPos ) ) ;d l c l ose ( l i b ) ;return 0 ;

}

This can be compiled using the following command:

gcc -o ctest2 ctest2.c -ldl

The-ldl tells gcc that the program needs thelibdl.so library to load dynamical libraries.

99

Page 101: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Chapter 12

Using Windows resources

12.1 The resource directive$R

Under WINDOWS, you can include resources in your executable or library using the{$R filename}directive. These resources can then be accessed through the standard WINDOWS API calls.

When the compiler encounters a resource directive, it just creates an entry in the unit.ppu file; itdoesn’t link the resource. Only when it creates a library or executable, it looks for all the resourcefiles for which it encountered a directive, and tries to link them in.

The default extension for resource files is.res. When the filename has as the first character an asterix(* ), the compiler will replace the asterix with the name of the current unit, library or program.

Remark: This means that the asterix may only be used after aunit , library or program clause.

12.2 Creating resources

The Free Pascal compiler itself doesn’t create any resource files; it just compiles them into the ex-ecutable. To create resource files, you can use some GUI tools as the Borland resource workshop;but it is also possible to use a WINDOWS resource compiler likeGNU windres. windres comes withtheGNU binutils, but the Free Pascal distribution also contains a version which you can use.

The usage of windres is straightforward; it reads an input file describing the resources to create andoutputs a resource file.

A typical invocation ofwindres would be

windres -i mystrings.rc -o mystrings.res

this will read themystrings.rc file and output amystrings.res resource file.

A complete overview of the windres tools is outside the scope of this document, but here are somethings you can use it for:

stringtables that contain lists of strings.

bitmaps which are read from an external file.

icons which are also read from an external file.

Version information which can be viewed with the WINDOWS explorer.

Menus Can be designed as resources and used in your GUI applications.

100

Page 102: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 12. USING WINDOWS RESOURCES

Arbitrary data Can be included as resources and read with the windows API calls.

Some of these will be described below.

12.3 Using string tables.

String tables can be used to store and retrieve large collections of strings in your application.

A string table looks as follows:

STRINGTABLE { 1, "hello World !"2, "hello world again !"3, "last hello world !" }

You can compile this (we assume the file is calledtests.rc) as follows:

windres -i tests.rc -o tests.res

And this is the way to retrieve the strings from your program:

program tests;

{$mode objfpc}

Uses Windows;

{$R *.res}

Function LoadResourceString (Index : longint): Shortstring;

beginSetLength(Result,LoadString(FindResource(0,Nil,RT_STRING),Index,@Result[1],SizeOf(Result)))

end;

VarI: longint;

beginFor i:=1 to 3 do

Writeln (Loadresourcestring(I));end.

The call toFindResource searches for the stringtable in the compiled-in resources. TheLoadStringfunction then reads the string with indexi out of the table, and puts it in a buffer, which can then beused. Both calls are in thewindows unit.

12.4 Inserting version information

The win32 API allows to store version information in your binaries. This information can be madevisible with the WINDOWS Explorer, by right-clicking on the executable or library, and selecting the’Properties’ menu. In the tab ’Version’ the version information will be displayed.

Here is how to insert version information in your binary:

101

Page 103: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 12. USING WINDOWS RESOURCES

1 VERSIONINFOFILEVERSION 4, 0, 3, 17PRODUCTVERSION 3, 0, 0, 0FILEFLAGSMASK 0FILEOS 0x40000FILETYPE 1{

BLOCK "StringFileInfo"{

BLOCK "040904E4"{

VALUE "CompanyName", "Free Pascal"VALUE "FileDescription", "Free Pascal version information extractor"VALUE "FileVersion", "1.0"VALUE "InternalName", "Showver"VALUE "LegalCopyright", "GNU Public License"VALUE "OriginalFilename", "showver.pp"VALUE "ProductName", "Free Pascal"VALUE "ProductVersion", "1.0"

}}

}

As you can see, you can insert various kinds of information in the version info block. The keywordVERSIONINFOmarks the beginning of the version information resource block. The keywordsFILEVERSION, PRODUCTVERSIONgive the actual file version, while the blockStringFileInfogives other information that is displayed in the explorer.

The Free Component Library comes with a unit (fileinfo) that allows to extract and view versioninformation in a straightforward and easy manner; the demo program that comes with it (showver)shows version information for an arbitrary executable or DLL.

12.5 Inserting an application icon

When WINDOWS shows an executable in the Explorer, it looks for an icon in the executable to showin front of the filename, the application icon.

Inserting an application icon is very easy and can be done as follows

AppIcon ICON "filename.ico"

This will read the filefilename.ico and insert it in the resource file.

12.6 Using a pascal preprocessor

Sometimes you want to use symbolic names in your resource file, and use the same names in yourprogram to access the resources. To accomplish this, there exists a preprocessor forwindres thatunderstands pascal syntax:fprcp. This preprocessor is shipped with the Free Pascal distribution.

The idea is that the preprocessor reads a pascal unit that has some symbolic constants defined in it,and replaces symbolic names in the resource file by the values of the constants in the unit:

As an example: consider the follwoing unit:

102

Page 104: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

CHAPTER 12. USING WINDOWS RESOURCES

unit myunit;

interface

ConstFirst = 1;Second = 2:Third = 3;

Implementationend.

And the following resource file:

#include "myunit.pp"

STRINGTABLE { First, "hello World !"Second, "hello world again !"Third, "last hello world !" }

if you invoke windres with the-preprocessor option:

windres --preprocessor fprcp -i myunit.rc -o myunit.res

Then the preprocessor will replace the symbolic names ’first’, ’second’ and ’third’ with their actualvalues.

In your program, you can then refer to the strings by their symbolic names (the constants) instead ofusing a numeric index.

103

Page 105: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Appendix A

Anatomy of a unit file

A.1 Basics

As described in chapter4, page45, unit description files (hereafter called PPU files for short), areused to determine if the unit code must be recompiled or not. In other words, the PPU files act asmini-makefiles, which is used to check dependencies of the different code modules, as well as verifyif the modules are up to date or not. Furthermore, it contains all public symbols defined for a module.

The general format of theppu file format is shown in figure (A.1).

To read or write the ppufile, the ppu unitppu.pas can be used, which has an object called tppufilewhich holds all routines that deal with ppufile handling. While describing the layout of a ppufile, themethods which can be used for it are presented as well.

A unit file consists of basically five or six parts:

1. A unit header.

2. A general information part (wrongly named interface section in the code)

3. A definition part. Contains all type and procedure definitions.

4. A symbol part. Contains all symbol names and references to their definitions.

5. A browser part. Contains all references from this unit to other units and inside this unit. Onlyavailable when theuf_has_browser flag is set in the unit flags

6. A file implementation part (currently unused).

A.2 reading ppufiles

We will first create an object ppufile which will be used below. We are opening unittest.ppu as anexample.

varppufile : pppufile;

begin{ Initialize object }

ppufile:=new(pppufile,init(’test.ppu’);{ open the unit and read the header, returns false when it fails }

104

Page 106: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX A. ANATOMY OF A UNIT FILE

if not ppufile.openfile thenerror(’error opening unit test.ppu’);

{ here we can read the unit }

{ close unit }ppufile.closefile;

{ release object }dispose(ppufile,done);

end;

Note: When a function fails (for example not enough bytes left in an entry) it sets theppufile.errorvariable.

A.3 The Header

The header consists of a record (tppuheader ) containing several pieces of information for recom-pilation. This is shown in table (A.1). The header is always stored in little-endian format.

Table A.1: PPU Header

offset size (bytes) description00h 3 Magic : ’PPU’ in ASCII03h 3 PPU File format version (e.g : ’021’ in ASCII)06h 2 Compiler version used to compile this module (major,minor)08h 2 Code module target processor0Ah 2 Code module target operating system0Ch 4 Flags for PPU file10h 4 Size of PPU file (without header)14h 4 CRC-32 of the entire PPU file18h 4 CRC-32 of partial data of PPU file (public data mostly)1Ch 8 Reserved

The header is already read by theppufile.openfile command. You can access all fields usingppufile.header which holds the current header record.

Table A.2: PPU CPU Field values

value description0 unknown1 Intel 80x86 or compatible2 Motorola 680x0 or compatible3 Alpha AXP or compatible4 PowerPC or compatible

Some of the possible flags in the header, are described in table (A.3). Not all the flags are described,for more information, read the source code ofppu.pas.

105

Page 107: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX A. ANATOMY OF A UNIT FILE

Table A.3: PPU Header Flag values

Symbolic bit flag name Descriptionuf_init Module has an initialization (either Delphi or TP style) section.uf_finalize Module has a finalization section.uf_big_endian All the data stored in the chunks is in big-endian format.uf_has_browser Unit contains symbol browser information.uf_smart_linked The code module has been smartlinked.uf_static_linked The code is statically linked.uf_has_resources Unit has resource section.

A.4 The sections

Apart from the header section, all the data in the PPU file is separated into data blocks, which permiteasily adding additional data blocks, without compromising backward compatibility. This is similarto both Electronic Arts IFF chunk format and Microsoft’s RIFF chunk format.

Each ’chunk’ (tppuentry ) has the following format, and can be nested:

Table A.4: chunk data format

offset size (bytes) description00h 1 Block type (nested (2) or main (1))01h 1 Block identifier02h 4 Size of this data block06h+ <variable> Data for this block

Each main section chunk must end with an end chunk. Nested chunks are used for record, class orobject fields.

To read an entry you can simply callppufile.readentry:byte , it returns thetppuentry.nrfield, which holds the type of the entry. A common way how this works is (example is for the sym-bols):

repeatb:=ppufile.readentry;case b of

ib<etc> : beginend;

ibendsyms : break;end;

until false;

The possible entry types are found inppu.pas, but a short description of the most common ones areshown in table (A.5).

Then you can parse each entry type yourself.ppufile.readentry will take care of skipping un-read bytes in the entry and reads the next entry correctly! A special function isskipuntilentry(untilb:byte):boolean;which will read the ppufile until it finds entryuntilb in the main entries.

Parsing an entry can be done withppufile.getxxx functions. The available functions are:

procedure ppufile.getdata(var b;len:longint);

106

Page 108: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX A. ANATOMY OF A UNIT FILE

Table A.5: Possible PPU Entry types

Symbolic name Location Descriptionibmodulename General Name of this unit.ibsourcefiles General Name of source files.ibusedmacros General Name and state of macros used.ibloadunit General Modules used by this units.inlinkunitofiles General Object files associated with this unit.iblinkunitstaticlibs General Static libraries associated with this unit.iblinkunitsharedlibs General Shared libraries associated with this unit.ibendinterface General End of General information section.ibstartdefs Interface Start of definitions.ibenddefs Interface End of definitions.ibstartsyms Interface Start of symbol data.ibendsyms Interface End of symbol data.ibendimplementation Implementation End of implementation data.ibendbrowser Browser End of browser section.ibend General End of Unit file.

function getbyte:byte;function getword:word;function getlongint:longint;function getreal:ppureal;function getstring:string;

To check if you’re at the end of an entry you can use the following function:

function EndOfEntry:boolean;

notes:

1. ppureal is the best real that exists for the cpu where the unit is created for. Currently it isextended for i386 andsingle for m68k.

2. theibobjectdef andibrecorddef have stored a definition and symbol section for them-selves. So you’ll need a recursive call. Seeppudump.pp for a correct implementation.

A complete list of entries and what their fields contain can be found inppudump.pp.

A.5 Creating ppufiles

Creating a new ppufile works almost the same as reading one. First you need to init the object andcall create:

ppufile:=new(pppufile,init(’output.ppu’));ppufile.createfile;

After that you can simply write all needed entries. You’ll have to take care that you write at least thebasic entries for the sections:

107

Page 109: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX A. ANATOMY OF A UNIT FILE

ibendinterfaceibenddefsibendsymsibendbrowser (only when you’ve set uf_has_browser!)ibendimplementationibend

Writing an entry is a little different than reading it. You need to first put everything in the entry withppufile.putxxx:

procedure putdata(var b;len:longint);procedure putbyte(b:byte);procedure putword(w:word);procedure putlongint(l:longint);procedure putreal(d:ppureal);procedure putstring(s:string);

After putting all the things in the entry you need to callppufile.writeentry(ibnr:byte)whereibnr is the entry number you’re writing.

At the end of the file you need to callppufile.writeheader to write the new header to thefile. This takes automatically care of the new size of the ppufile. When that is also done you can callppufile.closefile and dispose the object.

Extra functions/variables available for writing are:

ppufile.NewHeader;ppufile.NewEntry;

This will give you a clean header or entry. Normally this is called automatically inppufile.writeentry ,so there should be no need to call these methods.

ppufile.flush;

to flush the current buffers to the disk

ppufile.do_crc:boolean;

set to false if you don’t want that the crc is updated, this is necessary if you write for example thebrowser data.

108

Page 110: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX A. ANATOMY OF A UNIT FILE

Figure A.1: The PPU file format

109

Page 111: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Appendix B

Compiler and RTL source treestructure

B.1 The compiler source tree

All compiler source files are in several directories, normally the non-processor specific parts arein source/compiler. Subdirectories are present for each of the supported processors and targetoperating systems.

For more informations about the structure of the compiler have a look at the Compiler Manual whichcontains also some informations about compiler internals.

Thecompiler directory also contains a subdirectoryutils , which contains mainly the utilities forcreation and maintainance of the message files.

B.2 The RTL source tree

The RTL source tree is divided in many subdirectories, but is very structured and easy to understand.It mainly consists of three parts:

1. A OS-dependent directory. This contains the files that are different for each operating system.When compiling the RTL, you should do it here. The following directories exist:

• atari for the ATARI.

• amiga for the AMIGA .

• beos for BEOS. It has one subdirectory for each of the supported processors.

• freebsd for the FREEBSD platform.

• go32v1 For DOS, using the GO32v1 extender. Not maintained any more.

• go32v2 For DOS, using the GO32v2 extender.

• linux for LINUX platforms. It has one subdirectory for each of the supported processors.

• netbsd for NETBSD platforms. It has one subdirectory for each of the supported pro-cessors.

• palmos for the PALM OS Dragonball processor based platform.

• os2 for OS/2.

110

Page 112: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX B. COMPILER AND RTL SOURCE TREE STRUCTURE

• sunos for the SOLARIS platform. It has one subdirectory for each of the supportedprocessors.

• qnx for the QNX REALTIME PLATFORM.

• win32 for Win32 platforms.

• posix for posix interfaces (used for easier porting).

• unix for unix common interfaces (used for easier porting).

2. A processor dependent directory. This contains files that are system independent, but processordependent. It contains mostly optimized routines for a specific processor. The following dir-ectories exist:

• i386 for the Intel 80x86 series of processors.

• m68k for the Motorola 680x0 series of processors.

3. An OS-independent and Processor independent directory:inc. This contains complete units,and include files containing interface parts of units as well as generic versions of processorspecific routines.

111

Page 113: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Appendix C

Compiler limits

There are certain compiler limits inherent to the compiler:

1. Procedure or Function definitions can be nested to a level of 32. This can be changed bychanging themaxnesting constant.

2. Maximally 1024 units can be used in a program when using the compiler. You can change thisby redefining themaxunits constant in the compiler source file.

3. The maximum nesting level of pre-processor macros is 16. This can be changed by changingthe value ofmax_macro_nesting .

4. Arrays are limited to 2 GBytes in size in the default processor mode.

For processor specific compiler limitations refer to the Processor Limitations section in this guide(6.8).

112

Page 114: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Appendix D

Compiler modes

Here we list the exact effect of the different compiler modes. They can be set with the$Mode switch,or by command line switches.

D.1 FPC mode

This mode is selected by the$MODE FPCswitch. On the command-line, this means that you usenone of the other compatibility mode switches. It is the default mode of the compiler. This meansessentially:

1. You must use the address operator to assign procedural variables.

2. A forward declaration must be repeated exactly the same by the implementation of a function/-procedure. In particular, you can not omit the parameters when implementing the function orprocedure.

3. Overloading of functions is allowed.

4. Nested comments are allowed.

5. The Objpas unit is NOT loaded.

6. You can use the cvar type.

7. PChars are converted to strings automatically.

D.2 TP mode

This mode is selected by the$MODE TPswitch. It tries to emulate, as closely as possible, thebehavior of Turbo Pascal 7. On the command-line, this mode is selected by the-So switch.

1. Enumeration sizes default to a storage size of 1 byte if there are less than 257 elements.

2. You cannot use the address operator to assign procedural variables.

3. A forward declaration must not be repeated exactly the same by the implementation of a func-tion/procedure. In particular, you can omit the parameters when implementing the function orprocedure.

113

Page 115: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX D. COMPILER MODES

4. Overloading of functions is not allowed.

5. The Objpas unit is NOT loaded.

6. Nested comments are not allowed.

7. You can not use the cvar type.

D.3 Delphi mode

This mode is selected by the$MODE DELPHIswitch. It tries to emulate, as closely as possible, thebehavior of Delphi 4. On the command-line, this mode is selected by the-Sd switch.

1. You can not use the address operator to assign procedural variables.

2. A forward declaration must not be repeated exactly the same by the implementation of a func-tion/procedure. In particular, you not omit the parameters when implementing the function orprocedure.

3. Overloading of functions is not allowed.

4. Nested comments are not allowed.

5. The Objpas unit is loaded right after thesystem unit. One of the consequences of this is thatthe typeInteger is redefined asLongint .

D.4 GPC mode

This mode is selected by the$MODE GPCswitch. On the command-line, this mode is selected bythe-Sp switch.

1. You must use the address operator to assign procedural variables.

2. A forward declaration must not be repeated exactly the same by the implementation of a func-tion/procedure. In particular, you can omit the parameters when implementing the function orprocedure.

3. Overloading of functions is not allowed.

4. The Objpas unit is NOT loaded.

5. Nested comments are not allowed.

6. You can not use the cvar type.

D.5 OBJFPC mode

This mode is selected by the$MODE OBJFPCswitch. On the command-line, this mode is selectedby the-S2 switch.

1. You must use the address operator to assign procedural variables.

2. A forward declaration must be repeated exactly the same by the implementation of a function/-procedure. In particular, you can not omit the parameters when implementing the function orprocedure.

114

Page 116: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX D. COMPILER MODES

3. Overloading of functions is allowed.

4. Nested comments are allowed.

5. The Objpas unit is loaded right after thesystem unit. One of the consequences of this is thatthe typeInteger is redefined asLongint .

6. You can use the cvar type.

7. PChars are converted to strings automatically.

115

Page 117: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Appendix E

Using fpcmake

E.1 Introduction

Free Pascal comes with a special makefile tool,fpcmake, which can be used to construct aMakefilefor use withGNU make. All sources from the Free Pascal team are compiled with this system.

fpcmake uses a fileMakefile.fpc and constructs a fileMakefile from it, based on the settings inMakefile.fpc.

The following sections explain what settings can be set inMakefile.fpc, what variables are set byfpcmake , what variables it expects to be set, and what targets it defines. After that, some settingsin the resultingMakefile are explained.

E.2 Functionality

fpcmake generates a makefile, suitable for GNUmake, which can be used to

1. Compile units and programs, fit for testing or for final distribution.

2. Compile example units and programs separately.

3. Install compiled units and programs in standard locations.

4. Make archives for distribution of the generated programs and units.

5. Clean up after compilation and tests.

fpcmake knows how the Free Pascal compiler operates, which command line options it uses, how itsearches for files and so on; It uses this knowledge to construct sensible command-lines.

Specifically, it constructs the following targets in the final makefile:

all Makes all units and programs.

debug Makes all units and programs with debug info included.

smart Makes all units and programs in smartlinked version.

examples Makes all example units and programs.

shared Makes all units and programs in shared library version (currently disabled)

116

Page 118: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

install Installs all units and programs.

sourceinstall Installs the sources to the Free Pascal source tree.

exampleinstall Installs any example programs and units.

distinstall Installs all units and programs, as well as example units and programs.

zipinstall Makes an archive of the programs and units which can be used to install them on anotherlocation, i.e. it makes an archive that can be used to distribute the units and programs.

zipsourceinstall Makes an archive of the program and unit sources which can be used to distributethe sources.

zipexampleinstall Makes an archive of the example programs and units which can be used to installthem on another location, i.e. it makes an archive that can be used to distribute the exampleunits and programs.

zipdistinstall Makes an archive of both the normal as well as the example programs and units. Thisarchive can be used to install them on another location, i.e. it makes an archive that can beused to distribute.

clean Cleans all files that are produced by a compilation.

distclean Cleans all files that are produced by a compilation, as well as any archives, examples orfiles left by examples.

cleanall Same as clean.

info Produces some information on the screen about used programs, file and directory locations,where things will go when installing and so on.

Each of these targets can be highly configured, or even totally overridden by the configuration fileMakefile.fpc

E.3 Usage

fpcmake reads aMakefile.fpc and converts it to aMakefile suitable for reading byGNU maketo compile your projects. It is similar in functionality to GNUconfigure or Imake for making Xprojects.

fpcmake accepts filenames of makefile description files as its command-line arguments. For each ofthese files it will create aMakefile in the same directory where the file is located, overwriting anyexisting file with that name.

If no options are given, it just attempts to read the fileMakefile.fpc in the current directory and triesto construct aMakefile from it if the -m option is given. Any previously existingMakefile will beerased.

if the -p option is given, instead of aMakefile, aPackage.fpc is generated. APackage.fpc filedescribes the package and it’s dependencies on other packages.

Additionally, the following command-line options are recognized:

-p A Package.fpc file is generated.

-w A Makefile is generated.

-T targets Support only specified target systems.Targets is a comma-separated list of targets.Only rule for the specified targets will be written.

117

Page 119: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

-v Be more verbose.

-q be quiet.

-h Writes a small help message to the screen.

E.4 Format of the configuration file

This section describes the rules that can be present in the file that is fed tofpcmake.

The file Makefile.fpc is a plain ASCII file that contains a number of pre-defined sections as in aWINDOWS .ini-file, or a Samba configuration file.

They look more or less as follows:

[package]name=mysqlversion=1.0.5

[target]units=mysql_com mysql_version mysqlexamples=testdb

[require]libc=y

[install]fpcpackage=y

[default]fpcdir=../..

The following sections are recognized (in alphabetical order):

cleanSpecifies rules for cleaning the directory of units and programs. The following entries are recognized:

units names of all units that should be removed when cleaning. Don’t specify extensions, the make-file will append these by itself.

files names of files that should be removed. Specify full filenames.

compilerIn this section values for various compiler options can be specified, such as the location of severaldirectories and search paths.

The following general keywords are recognised:

options The value of this key will be passed on to the compiler as options.

version If a specific or minimum compiler version is needed to compile the units or programs, thenthis version should be specified here.

118

Page 120: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

The following keys can be used to control the location of the various directories used by the compiler:

unitdir A colon-separated list of directories that must be added to the unit search path of the com-piler.

librarydir A colon-separated list of directories that must be added to the library search path of thecompiler.

objectdir A colon-separated list of directories that must be added to the object file search path ofthe compiler.

targetdir Specifies the directory where the compiled programs should go.

sourcedir A space separated list of directories where sources can reside. This will be used for thevpath setting ofGNU make.

unittargetdir Specifies the directory where the compiled units should go.

includedir A colon-separated list of directories that must be added to the include file search path ofthe compiler.

sourcedir

DefaultThedefault section contains some default settings. The following keywords are recognized:

cpu Specifies the default target processor for which theMakefile should compile the units and pro-grams. By default this is determined from the default compiler processor.

dir Specifies any subdirectories that make should also descend in and make the specified target thereas well.

fpcdir Specifies the directory where all the Free Pascal source trees reside. Below this directory theMakefile expects to find thertl, fcl andpackages directory trees.

rule Specifies the default rule to execute.fpcmake will make sure that this rule is executed if makeis executed without arguments, i.e., without an explicit target.

target Specifies the default operating system target for which theMakefile should compile the unitsand programs. By default this is determined from the default compiler target.

DistTheDist section controls the generation of a distribution package. A distribution package is a setof archive files (zip files or tar files on unix systems) that can be used to distribute the package.

The following keys can be placed in this section:

destdir Specifies the directory where the generated zip files should be placed.

zipname Name of the archive file to be created. If no zipname is specified, this defaults to thepackage name.

ziptarget This is the target that should be executed before the archive file is made. This defaults toinstall .

119

Page 121: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

InstallContains instructions for installation of the compiler units and programs. The following keywordsare recognized:

basedir The directory that is used as the base directory for the installation of units. Default this isprefix appended with/lib/fpc/FPC_VERSION for LINUX or simply theprefix onother platforms.

datadir Directory where data files will be installed, i.e. the files specified with theFiles keyword.

fpcpackage A boolean key. If this key is specified and equalsy , the files will be installed as a fpcpackage under the Free Pascal units directory, i.e. under a separate directory. The directorywill be named with the name specified in thepackage section.

files extra data files to be installed in the directory specified with thedatadir key.

prefix is the directory below which all installs are done. This corresponds to the-prefix argumentto GNU configure. It is used for the installation of programs and units. By default, this is/usron LINUX , and/pp on all other platforms.

units extra units that should be installed, and which are not part of the unit targets. The units in theunits target will be installed automatically.

Units will be installed in the subdirectoryunits/$(OS_TARGET) of thedirbase entry.

PackageIf a package (i.e. a collection of units that work together) is being compiled, then this section is usedto keep package information. The following information can be stored:

name The name of the package. When installing it under the package directory, this name will beused to create a directory (unless it is overridden by one of the installation options)

version The version of this package.

main If the package is part of another package, this key can be specified to indicate which packageit is part of.

PrerulesAnything that is in this section will be inserted as-is in the makefilebeforethe makefile target rulesthat are generated by fpcmake. This means that any variables that are normally defined by fpcmakerules should not be used in this section.

RequiresThis section is used to indicate dependency on external packages (i.e units) or tools. The followingkeywords can be used:

fpcmake Minimal version of fpcmake that thismakefile.fpc needs.

packagesOther packages that should be compiled before this package can be compiled. Note thatthis will also add all packages these packages depend on to the dependencies of this package.By default, the Free Pascal Run-Time Library is added to this list.

120

Page 122: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

libc a boolean value that indicates whether this package needs the C library.

nortl a boolean that prevents the addition of the Free Pascal Run-Time Library to the required pack-ages.

unitdir These directories will be added to the units search path of the compiler.

packagedir List of package directories. The packages in these directories will be made as wellbefore making the current package.

tools A list of executables of extra tools that are required. The full path to these tools will be definedin the makefile as a variable with the same name as the tool name, only in uppercase. Forexample, the following definition:

tools=upx

will lead to the definition of a variable with the nameUPXwhich will contain the full path totheupx executable.

RulesIn this section dependency rules for the units and any other needed targets can be inserted. It will beincluded at the end of the generated makefile. Targets or ’default rules’ that are defined byfpcmakecan be inserted here; if they are not present, thenfpcmake will generate a rule that will call thegenericfpc_ version. For a list of standard targets that will be defined byfpcmake, see sectionE.2,page116.

For example, it is possible to define a targetall: . If it is not defined, thenfpcmake will generateone which simply callsfpc_all :

all: fpc_all

Thefpc_all rule will make all targets as defined in theTarget section.

TargetThis is the most important section of themakefile.fpc file. Here the files are defined which shouldbe compiled when the ’all’ target is executed.

The following keywords can be used there:

dirs A space separated list of directories where make should also be run.

exampledirs A space separated list of directories with example programs. The examples target willdescend in this list of directories as well.

examples A space separated list of example programs that need to be compiled when the user asksto compile the examples. Do not specify an extension, the extension will be appended.

loaders A space separated list of names of assembler files that must be assembled. Don’t specifythe extension, the extension will be appended.

programs A space separated list of program names that need to be compiled. Do not specify anextension, the extension will be appended.

rsts a list of rst files that needs to be converted to.po files for use withGNU gettext and interna-tionalization routines.

units A space separated list of unit names that need to be compiled. Do not specify an extension,just the name of the unit as it would appear un auses clause is sufficient.

121

Page 123: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

E.5 Programs needed to use the generated makefile

At least the following programs are needed by the generatedMakefile to function correctly:

cp a copy program.

date a program that prints the date.

install a program to install files.

make themake program, obviously.

pwd a program that prints the current working directory.

rm a program to delete files.

zip the zip archiver program. (on dos/windows/OS2 systems only)

tar the tar archiver program (on Unix systems only).

These are standard programs onLINUX systems, with the possible exception ofmake. For DOS orWINDOWS NT, they can be found in the filemakeutil.zip on the Free Pascal FTP site.

The following programs are optionally needed if you use some special targets. Which ones you needare controlled by the settings in thetools section.

cmp a DOS and WINDOWS NT file comparer.

diff a file comparer.

ppdep the ppdep depency lister. Distributed with Free Pascal.

ppufiles the ppufiles unit file dependency lister. Distributed with Free Pascal.

ppumove the Free Pascal unit mover.

sed thesed program.

upx the UPX executable packer.

All of these can also be found on the Free Pascal FTP site forDOSand WINDOWS NT. ppdep,ppufilesandppumove are distributed with the Free Pascal compiler.

E.6 Variables that affect the generated makefile

The makefile generated byfpcmake contains a lot of variables. Some of them are set in the makefileitself, others can be set and are taken into account when set.

These variables can be split in two groups:

• Directory variables.

• Compiler command-line variables.

Each group will be discussed separately.

122

Page 124: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

Directory variablesThe first set of variables controls the directories that are recognised in the makefile. They should notbe set in theMakefile.fpc file, but can be specified on the commandline.

INCDIR this is a list of directories, separated by spaces, that will be added as include directories tothe compiler command-line. Each directory in the list is prepended with-I and added to thecompiler options.

UNITDIR this is a list of directories, separated by spaces, that will be added as unit search director-ies to the compiler command-line. Each directory in the list is prepended with-Fu and addedto the compiler options.

LIBDIR is a list of library paths, separated by spaces. Each directory in the list is prepended with-Fl and added to the compiler options.

OBJDIR is a list of object file directories, separated by spaces, that is added to the object files path,i.e. Each directory in the list is prepended with-Fo .

Compiler command-line variablesThe following variable can be set on themake command-line, they will be recognised and integratedin the compiler command-line options.:

CREATESMART If this variable is defined, it tells the compiler to create smartlinked units. Adds-CX to the command-line options.

DEBUG If defined, this will cause the compiler to include debug information in the generated unitsand programs. It adds-gl to the compiler command-line, and will define theDEBUGdefine.

LINKSMART Defining this variable tells the compiler to use smartlinking. It adds-XX to thecompiler command-line options.

OPT Any options that you want to pass to the compiler. The contents ofOPTis simply added to thecompiler command-line.

OPTDEF Are optional defines, added to the command-line of the compiler. They get-d prependedto them.

OPTIMIZE if this variable is defined, this will add-OG2p3 to the command-line options.

RELEASE if this variable is defined, this will add the-Xs -OG2p3 -n options to the command-line options, and will define theRELEASEdefine.

STRIP if this variable is defined, this will add the-Xs option to the command-line options.

VERBOSE if this variable is defined, then-vnwi will be added to the command-line options.

E.7 Variables set byfpcmake

The makefile generated byfpcmake contains a lot of makefile variables.fpcmake will write all ofthe keys in themakefile.fpc as makefile variables in the formSECTION_KEYNAME. This meansthat the following section:

[package]name=mysqlversion=1.0.5

123

Page 125: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

will result in the following variable definitions:

override PACKAGE_NAME=mysqloverride PACKAGE_VERSION=1.0.5

Most targets and rules are constructed using these variables. They will be listed below, together withother variables that are defined byfpcmake.

The following sets of variables are defined:

• Directory variables.

• Program names.

• File extensions.

• Target files.

Each of these sets is discussed in the subsequent:

Directory variablesThe following compiler directories are defined by the makefile:

BASEDIR is set to the current directory if thepwd command is available. If not, it is set to ’.’.

COMPILER_INCDIR is a space-separated list of library paths. Each directory in the list is pre-pended with-Fl and added to the compiler options. Set by theincdir keyword in theCompiler section.

COMPILER_LIBDIR is a space-separated list of library paths. Each directory in the list is pre-pended with-Fl and added to the compiler options. Set by thelibdir keyword in theCompiler section.

COMPILER_OBJDIR is a list of object file directories, separated by spaces. Each directory in thelist is prepended with-Fo and added to the compiler options. Set by theobjdir keyword intheCompiler section.

COMPILER_TARGETDIR This directory is added as the output directory of the compiler, whereall units and executables are written, i.e. it gets-FE prepended. It is set by thetargtdirkeyword in theCompiler section.

COMPILER_TARGETUNITDIR If set, this directory is added as the output directory of the com-piler, where all units and executables are written, i.e. it gets-FU prepended.It is set by thetargtdir keyword in theDirs section.

COMPILER_UNITDIR is a list of unit directories, separated by spaces. Each directory in the listis prepended with-Fu and is added to the compiler options. Set by theunitdir keyword intheCompiler section.

GCCLIBDIR (LINUX only) is set to the directory wherelibgcc.a is. If needgcclib is set toTrue in the Libs section, then this directory is added to the compiler commandline with-Fl .

OTHERLIBDIR is a space-separated list of library paths. Each directory in the list is prependedwith -Fl and added to the compiler options. If it is not defined on linux, then the contents ofthe/etc/ld.so.conf file is added.

124

Page 126: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

The following directories are used for installs:

INSTALL_BASEDIR is the base for all directories where units are installed. By default, OnLINUX ,this is set to$(INSTALL_PREFIX)/lib/fpc/$(RELEASEVER) .On other systems, it is set to$(PREFIXINSTALLDIR) . You can also set it with thebasedirvariable in theInstall section.

INSTALL_BINDIR is set to$(INSTALL_BASEDIR) /bin on LINUX , and$(INSTALL_BASEDIR) /bin /$(OS_TARGET) on other systems. This is the place wherebinaries are installed.

INSTALL_DATADIR The directory where data files are installed. Set by theData key in theInstall section.

INSTALL_LIBDIR is set to$(INSTALL_PREFIX) /lib on LINUX ,and$(INSTALL_UNITDIR) on other systems.

INSTALL_PREFIX is set to/usr/local on LINUX , /pp on DOS or WINDOWS NT. Set by theprefix keyword in theInstall section.

INSTALL_UNITDIR is where units will be installed. This is set to$(INSTALL_BASEDIR) /units/$(OS_TARGET). If the units are compiled as a package,$(PACKAGE_NAME)is added to the directory.

Target variablesThe second set of variables controls the targets that are constructed by the makefile. They are createdby fpcmake, so you can use them in your rules, but you shouldn’t assign values to them yourself.

TARGET_DIRS This is the list of directories that make will descend into when compiling. Set bytheDirs key in theTarget section?

TARGET_EXAMPLES The list of examples programs that must be compiled. Set by theexampleskey in theTarget section.

TARGET_EXAMPLEDIRS the list of directories that make will descend into when compilingexamples. Set by theexampledirs key in theTarget section.

TARGET_LOADERS is a list of space-separated names that identify loaders to be compiled. Thisis mainly used in the compiler’s RTL sources. It is set by theloaders keyword in theTargets section.

TARGET_PROGRAMS This is a list of executable names that will be compiled. the makefileappends$(EXEEXT) to these names. It is set by theprograms keyword in theTargetsection.

TARGET_UNITS This is a list of unit names that will be compiled. The makefile appends$(PPUEXT)to each of these names to form the unit file name. The sourcename is formed by adding$(PASEXT) . It is set by theunits keyword in theTarget section.

ZIPNAME is the name of the archive that will be created by the makefile. It is set by thezipnamekeyword in theZip section.

ZIPTARGET is the target that is built before the archive is made. this target is built first. If suc-cessful, the zip archive will be made. It is set by theziptarget keyword in theZip section.

125

Page 127: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

Compiler command-line variablesThe following variables control the compiler command-line:

CPU_SOURCE the target CPU type is added as a define to the compiler command line. This isdetermined by the Makefile itself.

CPU_TARGET the target CPU type is added as a define to the compiler command line. This isdetermined by the Makefile itself.

OS_SOURCE What platform the makefile is used on. Detected automatically.

OS_TARGET What platform will be compiled for. Added to the compiler command-line with a-Tprepended.

Program namesThe following variables are program names, used in makefile targets.

AS The assembler. Default set toas.

COPY a file copy program. Default set tocp -fp.

COPYTREE a directory tree copy program. Default set tocp -frp.

CMP a program to compare files. Default set tocmp.

DEL a file removal program. Default set torm -f.

DELTREE a directory removal program. Default set torm -rf.

DATE a program to display the date.

DIFF a program to produce diff files.

ECHO an echo program.

FPC the Free Pascal compiler executable. Default set toppc386.exe

INSTALL a program to install files. Default set toinstall -m 644 on LINUX .

INSTALLEXE a program to install executable files. Default set toinstall -m 755 on LINUX .

LD The linker. Default set told.

LDCONFIG (LINUX only) the program used to update the loader cache.

MKDIR a program to create directories if they don’t exist yet. Default set toinstall -m 755 -d

MOVE a file move program. Default set tomv -f

PP the Free Pascal compiler executable. Default set toppc386.exe

PPAS the name of the shell script created by the compiler if the-s option is specified. This com-mand will be executed after compilation, if the-s option was detected among the options.

PPUMOVE the program to move units into one big unit library.

PWD the pwd program.

SED a stream-line editor program. Default set tosed.

UPX an executable packer to compress your executables into self-extracting compressed execut-ables.

ZIPPROG a zip program to compress files. zip targets are made with this program

126

Page 128: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

File extensionsThe following variables denote extensions of files. These variables include the. (dot) of the exten-sion. They are appended to object names.

ASMEXT is the extension of assembler files produced by the compiler.

LOADEREXT is the extension of the assembler files that make up the executable startup code.

OEXT is the extension of the object files that the compiler creates.

PACKAGESUFFIX is a suffix that is appended to package names in zip targets. This serves sopackages can be made for different OSes.

PPLEXT is the extension of shared library unit files.

PPUEXT is the extension of default units.

RSTEXT is the extension of the.rst resource string files.

SHAREDLIBEXT is the extension of shared libraries.

SMARTEXT is the extension of smartlinked unit assembler files.

STATICLIBEXT is the extension of static libraries.

Target filesThe following variables are defined to make targets and rules easier:

COMPILER is the complete compiler commandline, with all options added, after allMakefilevariables have been examined.

DATESTR contains the date.

UNITPPUFILES a list of unit files that will be made. This is just the list of unit objects, with thecorrect unit extension appended.

E.8 Rules and targets created byfpcmake

Themakefile.fpc defines a series of targets, which can be called by your own targets. They havenames that resemble default names (such as ’all’, ’clean’), only they havefpc_ prepended.

Pattern rulesThe makefile makes the following pattern rules:

units how to make a pascal unit form a pascal source file.

executableshow to make an executable from a pascal source file.

object file how to make an object file from an assembler file.

127

Page 129: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

Build rulesThe following build targets are defined:

fpc_all target that builds all units and executables as well as loaders. IfDEFAULTUNITSis defined,executables are excluded from the targets.

fpc_debug the same asfpc_all , only with debug information included.

fpc_exes target to make all executables inEXEOBJECTS.

fpc_loaders target to make all files inLOADEROBJECTS.

fpc_packagestarget to make all packages that are needed to make the files.

fpc_shared target that makes all units as dynamic libraries.

fpc_smart target that makes all units as smartlinked units.

fpc_units target to make all units inUNITOBJECTS.

Cleaning rulesThe following cleaning targets are defined:

fpc_clean cleans all files that result whenfpc_all was made.

fpc_distclean is the same as both previous target commands, but also deletes all object, unit andassembler files that are present.

archiving rulesThe following archiving targets are defined:

fpc_zipdistinstall Target to make a distribution install of the package.

fpc_zipinstall Target to make an install zip of the compiled units of the package.

fpc_zipexampleinstall Target to make a zip of the example files.

fpc_zipsourceinstall Target to make a zip of the source files.

The zip is made uzing theZIPEXE program. UnderLINUX , a .tar.gz file is created.

Installation rulesfpc_distinstall target which calls theinstall andexampleinstall targets.

fpc_install target to install the units.

fpc_sourceinstall target to install the sources (in case a distribution is made)

fpc_exampleinstall target to install the examples. (in case a distribution is made)

128

Page 130: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX E. USING FPCMAKE

Informative rulesThere is only one target which produces information about the used variables, rules and targets:fpc_info .

The following information about the makefile is presented:

• general configuration information: the location of the makefile, the compiler version, targetOS, CPU.

• the directories, used by the compiler.

• all directories where files will be installed.

• all objects that will be made.

• all defined tools.

129

Page 131: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Appendix F

Compiling the compiler

F.1 Introduction

The Free Pascal team releases at intervals a completely prepared package, with compiler and unitsall ready to use, the so-called releases. After a release, work on the compiler continues, bugs arefixed and features are added. The Free Pascal team doesn’t make a new release whenever theychange something in the compiler, instead the sources are available for anyone to use and compile.Compiled versions of RTL and compiler are also made daily, and put on the web.

There are, nevertheless, circumstances when the compiler must be recompiled manually. Whenchanges are made to compiler code, or when the compiler is downloaded through CVS.

There are essentially 2 ways of recompiling the compiler: by hand, or using the makefiles. Each ofthese methods will be discussed.

F.2 Before starting

To compile the compiler easily, it is best to keep the following directory structure (a base directoryof /pp/src is supposed, but that may be different):

/pp/src/Makefile/makefile.fpc/rtl/linux

/inc/i386/...

/compiler

When the makefiles should be used, the above directory tree must be used.

The compiler and rtl source are zipped in such a way that when both are unzipped in the samedirectory (/pp/src in the above) the above directory tree results.

There are 2 ways to start compiling the compiler and RTL. Both ways must be used, depending onthe situation. Usually, the RTL must be compiled first, before compiling the compiler, after whichthe compiler is compiled using the current compiler. In some special cases the compiler must becompiled first, with a previously compiled RTL.

How to decide which should be compiled first? In general, the answer is that the RTL should becompiled first. There are 2 exceptions to this rule:

130

Page 132: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX F. COMPILING THE COMPILER

1. The first case is when some of the internal routines in the RTL have changed, or if new in-ternal routines appeared. Since the OLD compiler doesn’t know about these changed internalroutines, it will emit function calls that are based on the old compiled RTL, and hence are notcorrect. Either the result will not link, or the binary will give errors.

2. The second case is when something is added to the RTL that the compiler needs to know about(a new default assembler mechanism, for example).

How to know if one of these things has occurred? There is no way to know, except by mailing theFree Pascal team. When the compiler cannot be recompiled when first compiling the RTL, then trythe other way.

F.3 Compiling usingmake

When compiling withmake it is necessary to have the above directory structure. Compiling thecompiler is achieved with the targetcycle .

Under normal circumstances, recompiling the compiler is limited to the following instructions (as-suming you start in directory/pp/src):

cd compilermake cycle

This will work only if the makefile is installed correctly and if the needed tools are present in thePATH. Which tools must be installed can be found in appendixE.

The above instructions will do the following:

1. Using the current compiler, the RTL is compiled in the correct directory, which is determinedby the OS. e.g. underLINUX , the RTL is compiled in directoryrtl/linux.

2. The compiler is compiled using the newly compiled RTL. If successful, the newly compiledcompiler executable is copied to a temporary executable.

3. Using the temporary executable from the previous step, the RTL is re-compiled.

4. Using the temporary executable and the newly compiled RTL from the last step, the compileris compiled again.

The last two steps are repeated 3 times, until three passes have been made or until the generatedcompiler binary is equal to the binary it was compiled with. This process ensures that the compilerbinary is correct.

Compiling for another target: When compiling the compiler for another target, it is necessary tospecify theOS_TARGETmakefile variable. It can be set to the following values:win32 , go32v2 ,os2 andlinux . As an example, cross-compilation for the go32v2 target from the win32 target ischosen:

cd compilermake cycle OS_TARGET=go32v2

This will compile the go32v2 RTL, and compile ago32v2 compiler.

When compiling a new compiler and the compiler should be compiled using an existing com-piled RTL, theall target must be used, and another RTL directory than the default (which is the../rtl/$(OS_TARGET) directory) must be indicated. For instance, assuming that the compiled RTLunits are in/pp/rtl , typing

131

Page 133: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX F. COMPILING THE COMPILER

cd compilermake cleanmake all UNITDIR=/pp/rtl

should use the RTL from the/pp/rtl dirrectory.

This will then compile the compiler using the RTL units in/pp/rtl. After this has been done, the’make cycle’ can be used, starting with this compiler:

make cycle PP=./ppc386

This will do themake cycle from above, but will start with the compiler that was generated bythemake all instruction.

In all cases, many options can be passed tomake to influence the compile process. In general, themakefiles add any needed compiler options to the command-line, so that the RTL and compiler canbe compiled. Additional options (e.g. optimization options) can be specified by passing them inOPT.

F.4 Compiling by hand

Compiling by hand is difficult and tedious, but can be done. The compilation of RTL and compilerwill be treated separately.

Compiling the RTLTo recompile the RTL, so a new compiler can be built, at least the following units must be built, inthe order specified:

loadersthe program stubs, that are the startup code for each pascal program. These files have the.asextension, because they are written in assembler. They must be assembled with theGNU asassembler. These stubs are in the OS-dependent directory, except forLINUX , where they arein a processor dependent subdirectory of theLINUX directory (i386 or m68k).

systemthesystem unit. This unit is named differently on different systems:

• Only on GO32v2, it’s calledsystem.

• For LINUX it’s calledsyslinux.

• For WINDOWS NT it’s calledsyswin32.

• For OS/2 it’s calledsysos2

This unit resides in the OS-dependent subdirectories of the RTL.

strings The strings unit. This unit resides in theinc subdirectory of the RTL.

dos Thedos unit. It resides in the OS-dependent subdirectory of the RTL. Possibly other units willbe compiled as a consequence of trying to compile this unit (e.g. onLINUX , thelinux unit willbe compiled, on go32, thego32 unit will be compiled).

objects the objects unit. It resides in theinc subdirectory of the RTL.

To compile these units on a i386, the following statements will do:

132

Page 134: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX F. COMPILING THE COMPILER

ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 -Us -Sg syslinux.ppppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 ../inc/strings.ppppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 dos.ppppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 ../inc/objects.pp

These are the minimum command-line options, needed to compile the RTL.

For another processor, thei386 should be changed into the appropriate processor. For anotheroperating system (target) thesyslinux should be changed in the appropriate system unit file, and thetarget OS setting (-T ) must be set accordingly.

Depending on the target OS there are other units that can be compiled, but which are not strictlyneeded to recompile the compiler. The following units are available for all plaforms:

objpas Needed for Delphi mode. Needs-S2 as an option. Resides in theobjpas subdirectory.

sysutils many utility functions, like in Delphi. Resides in theobjpas directory, and needs-S2 tocompile.

typinfo functions to access RTTI information, like Delphi. Resides in theobjpas directory.

math math functions like in Delphi. Resides in theobjpas directory.

mmx extensions for MMX class Intel processors. Resides in in thei386 directory.

getopts a GNU compatible getopts unit. resides in theinc directory.

heaptrc to debug the heap. resides in theinc directory.

Compiling the compilerCompiling the compiler can be done with one statement. It’s always best to remove all units fromthe compiler directory first, so something like

rm *.ppu *.o

on LINUX , and onDOS

del *.ppudel *.o

After this, the compiler can be compiled with the following command-line:

ppc386 -Tlinux -Fu../rtl/linux -di386 -dGDB pp.pas

So, the minimum options are:

1. The target OS. Can be skipped when compiling for the same target as the compiler which isbeing used.

2. A path to an RTL. Can be skipped if a correct fpc.cfg configuration is on the system. If thecompiler should be compiled with the RTL that was compiled first, this should be../rtl/OS(replace the OS with the appropriate operating system subdirectory of the RTL).

3. A define with the processor for which the compiler is compiled for. Required.

4. -dGDB. Required.

133

Page 135: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX F. COMPILING THE COMPILER

5. -Sg is needed, some parts of the compiler usegoto statements (to be specific: the scanner).

So the absolute minimal command line is

ppc386 -di386 -dGDB -Sg pp.pas

Some other command-line options can be used, but the above are the minimum. A list of recognisedoptions can be found in table (F.1).

Table F.1: Possible defines when compiling FPC

Define does whatTP Needed to compile the compiler with Turbo or Borland Pascal.GDB Support of the GNU Debugger (required switch).I386 Generate a compiler for the Intel i386+ processor family.M68K Generate a compiler for the M680x0 processor family.EXTDEBUG Some extra debug code is executed.MEMDEBUG Some memory usage information is displayed.SUPPORT_MMX only i386: enables the compiler switchMMXwhich

allows the compiler to generate MMX instructions.EXTERN_MSG Don’t compile the msgfiles in the compiler, always use

external messagefiles (default for TP).LOGSECONDPASS Write compiler node information in assembler output.NOOPT Do not include the optimizer in the compiler.

This list may be subject to change, the source filepp.pas always contains an up-to-date list.

134

Page 136: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Appendix G

Compiler defines during compilation

This appendix describes the possible defines when compiling programs using Free Pascal. A briefexplanation of the define, and when it is used is also given.

Table G.1: Possible defines when compiling using FPC

Define descriptionFPC_LINK_DYNAMIC Defined when the output will be linked dynamically.

This is defined when using the -XD compiler switch.FPC_LINK_STATIC Defined when the output will be linked statically.

This is the default mode.FPC_LINK_SMART Defined when the output will be smartlinked.

This is defined when using the -XX compiler switch.FPC_PROFILE Defined when profiling code is added to program.

This is defined when using the -pg compiler switch.FPK Always defined for Free Pascal.FPC Always defined for Free Pascal.VER1 Always defined for Free Pascal version 1.x.x.VER1_0 Always defined for Free Pascal version 1.0.x.ENDIAN_LITTLE Defined when the Free Pascal target is a little-endian processor

(80x86, Alpha, ARM).ENDIAN_BIG Defined when the Free Pascal target is a big-endian processor

(680x0, PowerPC, SPARC, MIPS).FPC_DELPHI Free Pascal is in Delphi mode, either using compiler switch -Sd or

using the$MODE DELPHIdirective.FPC_OBJFPC Free Pascal is in Delphi mode, either using compiler switch -S2 or

using the$MODE OBJFPCdirective.FPC_TP Free Pascal is in Turbo Pascal mode, either using compiler switch -So or

using the$MODE TPdirective.FPC_GPC Free Pascal is in GNU Pascal mode, either using compiler switch -Sp or

using the$MODE GPCdirective.

Remark: The ENDIAN_LITTLE andENDIAN_BIG defines were added starting from Free Pascal version1.0.5.

Remark: TheUNIX define was added starting from Free Pascal version 1.0.5. The BSD operating systems nolonger define LINUX starting with version 1.0.7.

135

Page 137: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

APPENDIX G. COMPILER DEFINES DURING COMPILATION

Table G.2: Possible CPU defines when compiling using FPC

Define When defined?CPU86 Free Pascal target is an Intel 80x86 or compatible.CPU87 Free Pascal target is an Intel 80x86 or compatible.CPUI386 Free Pascal target is an Intel 80386 or later.CPU68k Free Pascal target is a Motorola 680x0 or compatible.CPUM68020 Free Pascal target is a Motorola 68020 or later.CPU68 Free Pascal target is a Motorola 680x0 or compatible.CPUSPARC Free Pascal target is a SPARC v7 or compatible.CPUALPHA Free Pascal target is an Alpha AXP or compatible.CPUPOWERPC Free Pascal target is a 32-bit PowerPC or compatible.

Table G.3: Possible defines when compiling using target OS

Target operating system Defineslinux LINUX, UNIXfreebsd FREEBSD, BSD, UNIXnetbsd NETBSD, BSD, UNIXsunos SUNOS, SOLARIS, UNIXgo32v2 GO32V2, DPMIos2 OS2Windows 32-bit WIN32Classic Amiga AMIGAAtari TOS ATARIClassic Macintosh MACPalmOS PALMOSBeOS BEOS, UNIXQNX RTP QNX, UNIX

136

Page 138: Free Pascal Programmers’ manual · Free Pascal supports compiler directives in the source file. They are not the same as Turbo Pascal They are not the same as Turbo Pascal directives,

Appendix H

Operating system specific behavior

This appendix describes some special behaviors which vary from operating system to operating sys-tem. This is described in table (H.1). The GCC saved registers indicates what registers are savedwhen certain declaration modifiers are used.

Table H.1: Operating system specific behavior

Operating systems Min. param. stack align GCC saved registersAmiga 2 D2..D7,A2..A5Atari 2 D2..D7,A2..A5BeOS-x86 4 ESI, EDI, EBXDOS 2 ESI, EDI, EBXFreeBSD 4 ESI, EDI, EBXlinux-m68k D2..D7,A2..A5linux-x86 4 ESI, EDI, EBXMacOS-68k D2..D7,A2..A5NetBSD-x86 ESI, EDI, EBXNetBSD-m68k D2..D7,A2..A5OS/2 4 ESI, EDI, EBXPalmOS 2 D2..D7,A2..A5QNX-x86 ESI, EDI, EBXSolaris-x86 4 ESI, EDI, EBXWin32 4 ESI, EDI, EBX

137