Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Static libraries

A static library packs compiled code into one file that other programs link. The linker copies in the parts a program uses, so the program runs with nothing beside it.

'' A small library: tiko -lib mathlib.tiko writes libmathlib.a.
function Gcd( byval a as int64, byval b as int64 ) as int64
    do while b <> 0
        dim as int64 t = a mod b
        a = b
        b = t
    loop
    return abs( a )
end function

function Lcm( byval a as int64, byval b as int64 ) as int64
    return ( a \ Gcd( a, b ) ) * b
end function
'' #inclib names the library to link: libmathlib.a, found here.
#inclib "mathlib"

declare function Gcd( byval a as int64, byval b as int64 ) as int64
declare function Lcm( byval a as int64, byval b as int64 ) as int64

print "Gcd( 84, 36 ) ="; Gcd( 84, 36 )
print "Lcm( 4, 6 )   ="; Lcm( 4, 6 )

'' The smallest number that 1 to 20 all divide.
dim as int64 n = 1
for i as int32 = 2 to 20
    n = Lcm( n, i )
next
print "Lcm( 1..20 )  ="; n

Built with:

tiko -lib mathlib.tiko
tiko uselib.tiko

Output

Gcd( 84, 36 ) = 12
Lcm( 4, 6 )   = 12
Lcm( 1..20 )  = 232792560
  • tiko -lib mathlib.tiko compiles the file and writes libmathlib.a, on both targets.
  • #inclib "mathlib" tells the linker to use it. The name has no lib prefix and no extension. -l mathlib on the command line does the same.
  • The linker searched the current directory. -p dir on the command line, or #libpath "dir" in the source, adds other places to look.

The program declares the two functions itself. A library meant for others ships a header with those declarations, which every user includes. The parentheses in Lcm matter: \ binds more loosely than *, so a \ Gcd( a, b ) * b would divide by the product.

Activities

  1. Move the two declare lines into mathlib.ti and #include it.
  2. Add a Factorial function to the library and use it from the program.