OS X Programming Tips

From Free Pascal wiki
Jump to: navigation, search
Logo OSX.png

This article applies to macOS only.

See also: Multiplatform Programming Guide

Apple iOS new.svg

This article applies to iOS only.

See also: Multiplatform Programming Guide

English (en) | 日本語 (ja) | 한국어 (ko)

Other Interfaces

Platform specific Tips

Interfaces Development Articles

Installing Lazarus and Free Pascal

If you won't be using Subversion (SVN) to download and update the Free Pascal and Lazarus source code, you can ignore instructions elsewhere about installation on OS X. The following instructions assume you will only be installing Free Pascal and Lazarus using the disk image (.dmg extension) files available from Source Forge (stable version) or the Lazarus snapshot page.

Installing the Apple Developer Tools

Make sure the Apple Developer Tools are installed. Some of these tools are needed by Free Pascal. With OS X 10.3, they can be installed from the separate Xcode Tools CD that came with OS X. With OS X 10.4, they can be installed from the Xcode Tools folder on the Tiger Install DVD.

How to you know whether the Apple Developer Tools are installed? Look in /Library/Receipts. There should be a file named DeveloperTools.pkg if the tools are installed. You can also try running one of the tools. For example, open a Terminal window and enter "ld" (without quotes). If installed, the OS X linker will display its usage syntax.

Tip - The Free Pascal installer also requires that the gcc package be installed in case you should want to use Free Pascal with the Xcode IDE. With OS X 10.4, gcc is separate from the Developer Tools so be sure to install gcc4.0.pkg, too. If you have plenty of disk space, you can just install the Xcode metapackage (XcodeTools.mpkg), which installs all packages.

Xcode 4.3 and above

Xcode 4.3 and above no longer install the "Command Line Tools", which are needed by the IDE.

How to install the "Command Line Tools" via XCode (requires Apple Developer ID):

  1. Start XCode
  2. Preferences -> General -> Downloads -> Components
  3. Command Line Tools -> check Install

How to install from Web (requires Apple Developer ID):

https://developer.apple.com/downloads/index.action

In "Downloads for Apple Developers" choose "Command Line Tools". Download the dmg and install it.

Xcode 5 and above

In addition to what is written above about Xcode 4.3 and above, Xcode 5 and above no longer include gdb, the GNU debugger. This means that debugging in Lazarus does no longer work, unless you install gdb yourself. Another option is to install Xcode 4.x alongside Xcode 5.x and enter the path to GDB (e.g. /Applications/Xcode_4.6.3.app/Contents/Developer/usr/bin/gdb) into the debugger configuration field in the Lazarus settings dialog.

In Xcode 5 the command line tools are easily installed with the following terminal command:

xcode-select --install

See Installing_Lazarus_on_MacOS_X#Xcode_5.0.2B_compatibility_.28Mac_OS_X_10.8_and_10.9.29 for details.

Note: If you forgot to install the command line tools you might get a linker error like this:

ld: file not found: /usr/lib/crt1.o

Depending from your Xcode version alternative steps to install the command line developer tools may be to download them directly in the Xcode preferences window (see screenshots at Installing Lazarus on MacOS X) or to download them from developer.apple.com (please take care to install the command line tools that are correct exactly for your Xcode version).

Other Xcode versions

See Installing Lazarus on MacOS X for details.

Code Signing Requirements

Debugging under OSX 10.9 requires that the debugger (e.g. gdb) be code signed. The Debug and Release builds are set to code sign using a code signing certificate named lldb_codesign.

If you don't have one yet you will need to:

Launch /Applications/Utilities/Keychain Access.app

In Keychain Access select the "login" keychain in the "Keychains" list in the upper left hand corner of the window.

Select menu item: Keychain Access->Certificate Assistant->Create a Certificate

Set the following:

 Name = lldb_codesign
 Identity Type = Self Signed Root 
 Certificate Type = Code Signing
 Click Continue
 Click Continue
 Click Done

Click on the "My Certificates" Double click on your new lldb_codesign certificate Turn down the "Trust" disclosure triangle Change:

 When using this certificate: Always Trust

Enter your login password to confirm and make it trusted

The next steps are necessary on SnowLeopard, but are probably because of a bug how Keychain Access makes certificates.

Drag the new lldb_codesign certificate from the login keychain to the System keychain

In the Keychains pane of the main Keychain Access window to make a copy of this certificate in the System keychain.

You'll have to authorize a few more times, set it to be "Always trusted" when asked.

Switch to the System keychain

drag the copy of lldb_codesign you just made there onto the desktop.

Switch to Terminal, and run the following:

sudo security add-trust -d -r trustRoot -p basic -p codeSign -k /Library/Keychains/System.keychain ~/Desktop/lldb_codesign.cer

Right click on the "lldb_codesign" certificate in the "System" keychain (NOT "login", but the one in "System")

Delete the lldb_codesign.cer from your desktop.
Reboot

Clean and rebuild gdb and you must code sign gdb once installed.

cd/usr/local/bin
codesign -s lldb_codesign gdb

See Code Signing for Mac OS X for details.

Download Free Pascal and Lazarus

Download and install all three .dmg files from Source Forge or the Lazarus daily snapshot page:

 fpc.dmg
 fpcsrc.dmg
 lazarus.dmg

When done installing, you can delete these .dmg files.

Compatibility

Not every combination of Lazarus and Free Pascal is compatible with every installation of Mac OS X. Please refer to the following table in order to find the correct version for your development environment:

Lazarus Compatibility Matrix
Lazarus 1.0.0 Lazarus 1.0.2 Lazarus 1.0.4 Lazarus 1.0.6 Lazarus 1.0.8 Lazarus 1.0.10 Lazarus 1.0.12 Lazarus 1.0.14 Lazarus 1.2.0
Free Pascal (FPC) 2.6.0  FPC 2.6.2
PPC processors
Mac OS X 10.4 (Tiger) Incompatible Incompatible N/A Compatible Incompatible Incompatible Compatible* Compatible* Not tested
Mac OS X 10.5 (Leopard) Compatible Compatible N/A Compatible Compatible Compatible Compatible Compatible Compatible**
Intel processors
Mac OS X 10.4 (Tiger) Incompatible Incompatible Compatible Compatible Incompatible Incompatible With hack only Not tested Not tested
Mac OS X 10.5 (Leopard) Compatible Compatible Compatible Compatible Compatible Compatible Compatible Not tested Not tested
Mac OS X 10.6 (Snow Leopard) Compatible Compatible Compatible Compatible Compatible Compatible Compatible Compatible Compatible
Mac OS X 10.7 (Lion) Compatible Compatible Compatible Compatible Compatible Compatible Compatible Compatible Compatible
Mac OS X 10.8 (Mountain Lion) Compatible Compatible Compatible Compatible Compatible Compatible Compatible Compatible Compatible
Mac OS X 10.9 (Mavericks) Not tested Not tested Not tested Not tested Not tested Not tested Compatible* Compatible* Compatible*
Mac OS X 10.10 (Yosemite) Not tested Not tested Not tested Not tested Not tested Not tested Not tested Not tested Not tested
Mac OS X 10.11 (El Capitan) Not tested Not tested Not tested Not tested Not tested Not tested Not tested Not tested Not tested
macOS X 10.12 (Sierra) Not tested Not tested Not tested Not tested Not tested Not tested Not tested Not tested Not tested
Lazarus 1.2.2 Lazarus 1.2.4 Lazarus 1.2.6 Lazarus 1.4.0 Lazarus 1.4.2 Lazarus 1.4.4 Lazarus 1.6.0 Lazarus 1.6.2 Lazarus 1.6.4
 FPC 2.6.4  FPC 3.0.0 FPC 3.0.2
PPC processors
Mac OS X 10.4 (Tiger) Compatible N/A Compatible Incompatible Incompatible Incompatible Incompatible Incompatible Incompatible
Mac OS X 10.5 (Leopard) Compatible Compatible** Compatible Compatible** Compatible** Compatible** Not tested Not tested Not tested
Intel processors
Mac OS X 10.4 (Tiger) Not tested Not tested Not tested Incompatible Incompatible Incompatible Incompatible Incompatible Incompatible
Mac OS X 10.5 (Leopard) Compatible Not tested Not tested Not tested Not tested Not tested Not tested Not tested Not tested
Mac OS X 10.6 (Snow Leopard) Compatible Compatible Compatible Compatible Compatible Compatible Compatible Compatible Compatible
Mac OS X 10.7 (Lion) Compatible Compatible Compatible Not tested Not tested Not tested Compatible Compatible Compatible
Mac OS X 10.8 (Mountain Lion) Compatible Compatible Compatible Compatible* Compatible* Compatible* Compatible* Compatible* Compatible*
Mac OS X 10.9 (Mavericks) Compatible* Compatible* Compatible* Compatible* Compatible* Compatible* Compatible* Compatible* Compatible*
Mac OS X 10.10 (Yosemite) Not tested Not tested Compatible* Compatible* Compatible* Compatible* Compatible* Compatible* Compatible*
Mac OS X 10.11 (El Capitan) Not tested Not tested Not tested Not tested Not tested Compatible* Compatible* Compatible* Compatible*
macOS X 10.12 (Sierra) Not tested Not tested Not tested Not tested Not tested Not tested Compatible* Compatible* Compatible*

*Restrictions apply to debugging with GDB. **Not available as pre-built installer. Compiling from source required.

See also Installing Lazarus on MacOS X for details.

Start Lazarus

If you installed via package: Just double-click on the lazarus icon in the install folder (/usr/local/share/lazarus).

You can also start the carbon IDE from a terminal with:

cd /usr/local/share/lazarus
open lazarus.app

Note: Do not start the lazarus executable directly (as under linux and windows). OS X needs the lazarus.app directory.

If you compiled the gtk version open an X11 window and enter:

cd /usr/local/share/lazarus  // or whatever path you chose
./lazarus

If Lazarus complains about not being able to find the Free Pascal compiler, choose Tools -> Options in the Lazarus IDE and enter /usr/local/bin/ppcppc in the Compiler path box (/usr/local/bin/ppc386 on Intel Macs).

If installed Lazarus won't start correctly, you can change the option by a text editor. Check your environmentoptions.xml file, found at the ~/.lazarus directory. You can access this directory via a terminal or via Finder using "move to folder" submenu in "Move" (Command + Shift + G). Open this file with your favourite editor and search for a line alike:

<CompilerFilename Value="/usr/local/bin/XXX">

Here, XXX is the compiler name, must be "ppc386" on Intel Macs or "ppcppc" on PowerPC Macs. Correct it according as your Mac's CPU type. The alias "fpc" also will work.

Tip - See the section below on creating an app bundle for information on how to start a GTK Lazarus by double clicking it or dropping it on the dock. See Lazarus IDE Shortcuts.

Qt Interface

If you have any interest in using the Qt widgetset with Lazarus, install the Qt interface framework. See the Qt Interface Mac page for complete details on using it with OS X.

Gtk interface

This is not recommended. It is unlikely that using the Gtk interface in Mac OS X is a good option for anyone, but for people interested on this, please read this page: GTK2 Interface#Using the GTK2 interface under Mac OS X

Cross compiling OSX applications on Linux

See Cross compiling OSX on Linux

Choice of Lazarus LCL widgetsets

With OS X there are various widgetsets which can be used with Lazarus. Each has its strengths and weaknesses.

Carbon widgetset (see the Carbon Interface page)

Pros Cons
All standard LCL controls working The entire Carbon framework was deprecated by Apple. It is not available in 64 bit Mac OS X applications
No additional libraries or frameworks to install; uses Carbon framework included with OS X Only relevant to OS X
Native OS X look and feel

Cocoa widgetset (see the Cocoa Interface page)

Pros Cons
No additional libraries or frameworks to install; uses the Cocoa framework included with OS X Some LCL controls not yet working
Native OS X look and feel Only relevant to OS X

GTK widgetset

Pros Cons
All standard LCL controls working Ugly; clunky common dialogs; doesn't look like Mac software
This widgetset is well tested Requires X11 and bulky GTK to be installed to run Lazarus or any GUI apps created with Lazarus
Have to start Lazarus at command line -- can't double-click Lazarus or place on dock (same with GUI apps) -- although see next topic for how you can add this capability yourself


Qt widgetset (see the Qt Interface Mac page)

Pros Cons
Native OS X look and feel Requires the Qt interface framework to be installed to run app, which is rather large
All standard LCL controls working
The Qt widgetset also available for other platforms, so any effort put into developing Qt widgetset benefits multiple platforms
The Qt interface provides rich functionality
The Qt widgetset is easier to develop than other widgetsets

Creating an app bundle for a GTK application

With OS X, you need to create an app bundle for an executable file in order to drop it on the dock or launch it by double-clicking. An app bundle is really just a special folder that can have the same name as the executable, but with an .app extension. Finder doesn't display the .app extension, although you'll see it if you use ls in a Terminal window.

The Carbon and Qt pages both explain how to create an app bundle for apps compiled with those widgetsets. With a GTK app, it's a bit more complicated since X11 always has to be running in order to run the app. Copy and paste the following script to file create_gtk_app.sh, use chmod +x on the file so OS X will let you run it, then run it as follows to create an app bundle (substitute the name of your own GUI app compiled with the GTK widgetset):

./create_gtk_app.sh execfile

You can even use this script to create an app bundle for Lazarus itself, since it's a GTK app. Just change to wherever you want to create the app bundle (for example, the Applications folder) and run the script:

[path_to_script]/create_gtk_app.sh lazarus

Now you can drag and drop the resulting Lazarus app bundle onto the dock just like any other application.

For more information, study the script.

Tip: In the script below, one of the lines is really long and may get chopped off when you print this page (but why would you print this page only to type it in again when you can just copy and paste?) --BigChimp 12:37, 24 November 2013 (CET). Here's the line on two lines. Just be sure it's all one line in your script file.

 echo '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" 
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' >>$plistfile
#!/bin/sh
# Force Bourne shell in case tcsh is default.
#
appname=$1
appfolder=$appname.app
macosfolder=$appfolder/Contents/MacOS
plistfile=$appfolder/Contents/Info.plist
if [ $appname = "lazarus" ]
then
  appfile=/usr/local/share/lazarus/lazarus
else
  appfile=$appname
fi
#
if [ "$appname" = "" ]
then
  echo "Usage: $0 executable_file"
  echo "Creates .app bundle (folder) for executable file that uses GTK widgetset"
elif ! [ -e $appfile ]
then
  echo "$appfile does not exist"
elif [ -e $appfolder ]
then
  echo "$appfolder already exists"
else
  echo "Creating $appfolder..."
  mkdir $appfolder
  mkdir $appfolder/Contents
  mkdir $appfolder/Contents/MacOS
  mkdir $appfolder/Contents/Resources
#
  if [ $appname = "lazarus" ]
  then
# This is special case for lazarus IDE.
# Create a script file in .app folder that starts X11, then Lazarus.
    echo '#!/bin/sh' >$macosfolder/$appname.sh
    echo '# This script starts X11, then Lazarus.' >>$macosfolder/$appname.sh
    echo 'open -a x11' >>$macosfolder/$appname.sh
    echo "export DISPLAY=':0.0'" >>$macosfolder/$appname.sh
    echo 'open -a '$appfile >>$macosfolder/$appname.sh                #IMPORTANT! If you're running TCSH, or other,
    chmod +x $macosfolder/$appname.sh                                 # "open -a" doesn't work. Use "open" instead
  else
# Instead of copying executable into .app folder after each compile,
# simply create a symbolic link to executable.
    ln -s ../../../$appname $macosfolder/$appname
# Create a little script file in .app folder that opens executable with X11.
    echo '#!/bin/sh' >$macosfolder/$appname.sh
    echo '# This script opens the executable file with X11.' >>$macosfolder/$appname.sh
    echo 'open ${0/%.sh}' >>$macosfolder/$appname.sh
    chmod +x $macosfolder/$appname.sh
  fi
#
# Create PkgInfo file.
  echo "APPL????" >$appfolder/Contents/PkgInfo
#
# Create information property list file (Info.plist).
  echo '<?xml version="1.0" encoding="UTF-8"?>' >$plistfile
  echo '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' >>$plistfile
  echo '<plist version="1.0">' >>$plistfile
  echo '<dict>' >>$plistfile
  echo '  <key>CFBundleDevelopmentRegion</key>' >>$plistfile
  echo '  <string>English</string>' >>$plistfile
  echo '  <key>CFBundleExecutable</key>' >>$plistfile
  echo '  <string>'$appname'.sh</string>' >>$plistfile
  echo '  <key>CFBundleInfoDictionaryVersion</key>' >>$plistfile
  echo '  <string>6.0</string>' >>$plistfile
  echo '  <key>CFBundlePackageType</key>' >>$plistfile
  echo '  <string>APPL</string>' >>$plistfile
  echo '  <key>CFBundleSignature</key>' >>$plistfile
  echo '  <string>????</string>' >>$plistfile
  echo '  <key>CFBundleVersion</key>' >>$plistfile
  echo '  <string>1.0</string>' >>$plistfile
  echo '  <key>CSResourcesFileMapped</key>' >>$plistfile
  echo '  <true/>' >>$plistfile
  echo '</dict>' >>$plistfile
  echo '</plist>' >>$plistfile
fi

Adding an icon to your app bundle

5.1 Use OS X's Icon Composer or a similar program to create your app's icon file (.icns extension).

5.2 Copy the .icns file to your app bundle's Resources folder. For example, from the command line:

cp -p myapp.icns myapp.app/Contents/Resources

5.3 Add the following key to your app bundle's Info.plist file:

<key>CFBundleIconFile</key>
<string>myapp.icns</string>

5.4 Sometimes Finder doesn't "refresh" an app to use the new icon, continuing instead to show the default icon. You can try these things to force Finder to use the new icon:

  • Log out and back in again.
  • Drag (move) your application to a different folder, then back again.
  • Restart Finder (Esc-Option-Apple keys).

You shouldn't have this problem with Finder when you install your app on other computers. Finder apparently only has trouble when you change the icon from what it was when the app was first created.

Using stdout for logging and debugging

Unix systems usually allows output to stdout for the GUI applications (while for Windows it requires to create a console object for stdout, use file handle as stdout or link the application as non-GUI). The output is really useful for debugging and logging purposes.


MacOSX GUI applications (the ones created by Lazarus) are deployed as bundles. The bundled application conceals the output. However, it's possible to see the output using Console application.


It's also possible to see the output, but launching the application from Terminal.

  • Launch Terminal
  • enter to the project directory
  • enter the bundle (the directory with the .app extension), and launch the executable
cd project.app/Contents/MacOS
./project
  • once project launched the output will be seen in the Terminal window

OSXStdOutExample.png

Deploying an executable, Compiling under 10.6 for older version of Mac OS X

When compiling an application on Mac OS X without any special options, the application is only guaranteed to work on that particular major Mac OS X release and later (e.g., when compiling under Mac OS X 10.6.8, the application is only guaranteed to work on Mac OS X 10.6.8 and later).

Here is an example of an error that you may encounter when running an application compiled for Mac OS X 10.5 under Mac OS X 10.4 in case you use the widestring manager:

dyld: Library not loaded: /usr/lib/libiconv.2.dylib
  Referenced from: /Volumes/..../yourprogram
  Reason: Incompatible library version: yourprogram requires version 7.0.0 or later, but libiconv.2.dylib provides version 5.0.0
Trace/BPT trap

Here is an example of an error that you may encounter when running an application compiled for Mac OS X 10.6.8 under Mac OS X 10.6.7:

Runtime error 203

FPC 2.6.2 and above

http://wiki.freepascal.org/FPC_New_Features_2.6.2#Support_for_specifying_and_querying_the_deployment_version

Adding the custom options only when compiling for OS X

To add the above custom options only when compiling for OS X add to Project / Compiler options / IDE macros / Conditionals:

if TargetOS = 'darwin' then begin
  UsageCustomOptions += ' -WM10.6';
end;

FPC 2.6.1 and below

To make sure that it runs under previous Mac OS X releases, use the -macosx_version_min linker parameter and link against the appropriate SDK (e.g. -XR/Developer/SDKs/MacOSX10.5.sdk/ or -XR/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk/). For example, to compile an application that should work on Mac OS X 10.5 and higher:

Add to /etc/fpc.cfg OR to Project / Compiler options / Other / Custom options:

-k-macosx_version_min -k10.5
-XR/Developer/SDKs/MacOSX10.5.sdk/

The 10.4 SDK is the only one with a special name (10.4u instead of 10.4). Other SDK names simply contain the major Mac OS X version number: MacOSX10.5.sdk, MacOSX10.6.sdk, ...

Note: The path /Developer depends on where you installed the Apple developer tools, and may be different if you chose a different location. Do not assume it will always be /Developer.

The 10.7 is by default:

-k-macosx_version_min -k10.7
-XR/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk/

For targeting Mac OS X 10.4 (Tiger) the following settings are required:

-k-macosx_version_min -k10.4
-XR/Developer/SDKs/MacOSX10.4u.sdk/

Adding the custom options only when compiling for OS X

To add the above custom options only when compiling for OS X add to Project / Compiler options / IDE macros / Conditionals:

if TargetOS = 'darwin' then begin
  UsageCustomOptions += ' -k-macosx_version_min -k10.5';
  UsageCustomOptions += ' -XR/Developer/SDKs/MacOSX10.5.sdk/';
end;

Useful tools to download and install

TextWrangler

Every programmer needs a great text editor, but OS X's TextEdit app is not it. Instead, download and install TextWrangler, a freeware text editor that can highlight Pascal syntax, even highlight script file syntax.

Other editors include AlphaX, BBedit, or you can use OS X's Xcode IDE to edit text files.

Sogudi (discontinued :()

OS X's man pages (manual pages) are scandalously hard to use and indicate OS X's Unix heritage. Sogudi is a little add-on for OS X's Safari Web browser. Once installed, you can type "man:" in Safari's URL box, followed by the name of the command whose manual you want to view. For example, to view the manual for the grep command, enter the following:

man:grep

Now you can scroll up and down in the manual, print it, even search it just like you do a Web page.

NeoOffice

NeoOffice is an OS X version of OpenOffice.org that actually looks and behaves like an OS X app. Once you've started using Neo you'll never want to use the plain X11 version of OO again.

Unix and Open Source downloads

Apple provides downloads of numerous free applications, many of which have been ported from Unix and run under X11, such as the venerable Gimp.

Onyx

Onyx is a useful maintenance tool for OS X.

Cyberduck

Need an FTP client app for OS X? Cyberduck is an open source FTP client specifically designed for OS X.

Useful commands and tools included with OS X

open

Use open to start an application or open a file from the command line. This is useful when you’re working in a terminal window and don’t want to fire up the app and navigate to where you’re working just to open a file there. For example, to open a Pascal file in the current directory in TextWrangler, enter the following:

open –a textwrangler myfile.pas

zip / unzip

These standard command-line programs are installed with OS X’s Xcode tools (on a separate CD with OS X 10.3).

Console

Drag this app from /Applications/Utilities and drop it on the dock so you always have it handy. Launch it whenever you want to see messages or errors outputted to the console by GUI apps (for example, when they crash). Invaluable for debugging.

Activity Monitor

This app is also in /Applications/Utilities and is useful for monitoring CPU and disk usage.

otool / install_name_tool

Use otool to display information about an executable file or library. For example, enter the following to see information about Lazarus:

cd /usr/local/share/lazarus
otool –L lazarus

This shows that Lazarus is dependent on various libraries in /sw/lib, /usr/X11R6/lib and /usr/lib, as you would expect.

Use install_name_tool with the –change switch to change where an executable file or library looks for a library that it requires.

Grab

Use Grab (in /Applications/Utilities) to create a screenshot or window shot, then save it to a disk file.

Icon Composer

Use Icon Composer (in /Developer/Applications/Utilities) to create icon files (.icns) for use with your .app bundles.

PackageMaker / Disk Utility

Use these apps to create disk image (.dmg) files for deploying your apps. See Deploying Your Application for more information.

PackageMaker is in /Developer/Applications/Utilities. Disk Utility is in /Applications/Utilities. You can drag and drop both of them on the dock.

Script Editor / osascript

Use Script Editor to edit, compile and run AppleScript files. It’s located in /Applications/AppleScript.

Use osascript to execute an AppleScript command or file from the command line or from a script file. For more information, enter man:osascript in Safari once you have Sogudi installed (see above).

Commonly used Unix commands

If you’re coming to OS X from Windows, you may find some of its Unix terminal commands confusing. Here are some equivalents. For more information about a command, enter man:command in Safari once you have Sogudi installed (see above).

Action Windows command prompt window OS X Terminal or X11 window
Change to a different directory cd cd
Make a new directory mkdir mkdir
Delete a directory rmdir rmdir
List file directory in chronological order with detail dir /od ls -ltr
Copy a file, preserving its date-time stamp copy cp -p
Display contents of a text file type cat
Delete a file erase rm
Move a file move mv
Rename a file ren mv
Find a file dir /s find
Grep a file findstr grep
Display differences between two text files fc diff
Change file attributes attrib chmod
“Super-user” root authorization N/A sudo
Create symbolic link to a file or directory N/A ln
Shrink executable file size strip (included w/ Free Pascal) strip


Mac OS X Libraries

Using a library in a Mac application

Many software projects use external libraries to complement their functionality. For example, OpenAL might be utilized to provide sound support, or FreeType might be utilized to provide font rendering support for FCL-Image. Mac OS X already comes with a number of open source libraries installed, being that OpenAL is one of them. If one of these libraries is utilized, one should simply add the corresponding import unit to the uses clause and start using the library. To use other open source libraries which aren't included with Mac OS X, the easiest way is by grabbing a pre-compiled library from the application bundle of popular open source applications. FreeType for example is included inside the application bundle from Gimp in the path Gimp.app/Resources/lib/libfreetype.6.dylib. Another option is downloading the source code from the library and building it manually, but compiling a C library is usually an unpleasant task for Pascal developers.

So, again in the previous example, let's say that an application requires the FreeType library. One can grab the libfreetype.6.dylib file from Gimp and then place it in a location of our source code tree, for example ../Mac/libfreetype.dylib relative to the path of the main project file, which is where the executable is placed. To properly link the application the Free Pascal command line option "-Fl../Mac" should be added, so that this path is added to the library search path. The linker will then find the library in this location and read the install path which is written inside it. At runtime the linker will search for the library in this install path. To change the install path to our desired one, the command line application install_name_tool, which comes with the Apple Developer Tools, can be used. It can be utilized with the following command line command:

install_name_tool libfreetype.dylib -id @executable_path/../Resources/lib/libfreetype.dylib

One can then verify if this command worked by using the command:

otool -D libfreetype.dylib

It should return the written path. When building the application bundle, we should copy the libfreetype.dylib file to the directory Resources/lib. The install_name_tool command uses the @executable_path macro to set a install path relative to the executable, which is inside the MacOS folder in the application bundle. Now the application can be built, the bundle and be built and then the application can be run and it will load the library correctly from the application bundle.

Using a library installed using fink

For using libraries, which were installed using fink, you need to add the path to the libraries. The default is /sw/lib. Adding the option -Fl/sw/lib to the command line tells the linker where to find the libraries. The resulting application is fine for distribution with fink, but in order to run without fink, you have to make a "standalone" version. There are several possibilities to achieve this, one of them will be outlined here: First copy the .dylib file into the application bundle, for example to Contents/MacOS/ next to the executable binary. Then, adjust the paths install_name_tool:

First, change the path of the library in the executable:

install_name_tool  -change /sw/lib/libfreetype.dylib @executable_path/libfreetype.dylib @executable_path/your_executable_binary

Second, adjust the path in the library

install_name_tool  -id @executable_path/libfreetype.dylib @executable_path/libfreetype.dylib
install_name_tool  -change /sw/lib/libfreetype.dylib @executable_path/libfreetype.dylib @executable_path/libfreetype.dylib

The complete list of libraries in your executable can be obtained with:

otool -L @executable_path/your_executable_binary | grep version | cut -f 1 -d ' '

The list with libraries from fink only without libraries from /usr/lib and /System/Library gives this command:

otool -L @executable_path/your_executable_binary | grep version | cut -f 1 -d ' ' | grep -v \/System\/Library | grep -v \/usr\/lib

With this a script can be created, which loops over all libraries from fink in the executable.

Beware of the fact that the libraries can itself call libraries from fink. You have to adjust them as well.

Another important point of libraries from fink is, that they have only one architecture, i.e. i386, ppc, x86_64 or ppc64. For a universal application, you have to combine single architecture libraries with lipo.

Bundle Tricks

How to obtain the path to the Bundle

The ProgramDirectory function should be used instead of ExtractFilePath(Application.EXEName) which doesn't return the right result on OS/X.

Creating Universal binaries

Lazarus will create an application tuned for a single CPU. With the carbon version of the lcl, this is either PowerPC or Intel i386 (32bit). You may want to distribute your application as a 'Universal Binary', allowing users that may have either a PowerPC or Intel computer to use the program. To do this, you need to compile two versions of your application: one with PowerPC as the target CPU and one as Intel. Next, you need to stitch these two executables together using the OS X program "lipo" (installed with the other OS X developer tools required by Lazarus). For example, consider two versions of the application 'myprogram'. One in the 'ppc' folder compiled for PowerPC and one in the 'intel' folder compiled for Intel CPUs. You can then combine these two to a univeral application by running this command:

 lipo -create ./ppc/myproj ./intel/myproj -output ./myproj

Now, copy the newly created application myproj inside your .app folder.

A note on 64 bit binaries: Depending on the version of OS X and after corresponding (cross-)compilers are installed, programs, which do not use the lcl, can also be built as ppc64 or x86_64 binaries, in particular command line utilities. lipo is used in the same way to put them into universal binaries.

Code Signing

iOS requires your application to be code signed, and it is also required in some circumstances under Mac OS X. Code signing a program that has been written in Lazarus or Free Pascal requires only a few steps that are described in the article Code Signing for Mac OS X.

Locale settings (date & time separator, currency symbol, ...)

On OS X, like on other Unix platforms, the RTL does not load the locale settings by default. They can be initialised in three ways.

Automatic initialisation based on the System Preferences settings

In FPC 2.7.1 and later, adding the iosxlocale unit to the uses clause will initialise the locale settings using the settings from the System Preferences. This unit is not available in older versions of FPC.

Automatic initialisation based on the settings in the Unix layer

Adding the clocale unit to the uses clause will cause the locale settings to be initialised using the configuration set at the Unix layer of OS X (based on the LANG and related environment variables). This unit is also available on other Unix-like platforms.

Manual initialisation

  • Hardcoded:
 
 // use in initialization or in onCreate of the main form
  DateSeparator := '.';
  ShortDateFormat := 'dd.mm.yyyy';
  LongDateFormat := 'd. mmmm yyyy';

[1]

  • Partially replicating the functionality of the iosxlocale unit:
 
 
uses
  {$IFDEF LCLCarbon}
  , MacOSAll, CarbonProc
  {$ENDIF}
 
var
{$IFDEF LCLCarbon}
  theFormatString: string;
  theFormatter: CFDateFormatterRef;
{$ENDIF}
 
procedure GetMacDateFormats;
begin
  {$IFDEF LCLCarbon}
  theFormatter := CFDateFormatterCreate(kCFAllocatorDefault, CFLocaleCopyCurrent, kCFDateFormatterMediumStyle, kCFDateFormatterNoStyle);
  theFormatString := CFStringToStr(CFDateFormatterGetFormat(theFormatter));
  if pos('.', theFormatString) > 0 then
    DefaultFormatSettings.DateSeparator := '.'
  else if pos('/', theFormatString) > 0 then
    DefaultFormatSettings.DateSeparator := '/'
  else if pos('-', theFormatString) > 0 then
    DefaultFormatSettings.DateSeparator := '-';
  DefaultFormatSettings.ShortDateFormat := theFormatString;
  CFRelease(theFormatter); 
  theFormatter := CFDateFormatterCreate(kCFAllocatorDefault, CFLocaleCopyCurrent, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle);
  theFormatString := CFStringToStr(CFDateFormatterGetFormat(theFormatter));
  DefaultFormatSettings.LongDateFormat := theFormatString;
  CFRelease(theFormatter); 
  {$ENDIF}
end;

If the procedure GetMacDateFormats is called in the beginning of the program's main unit the "International" settings of systems preferences are used.

Apple-specific UI elements

AppName/Apple main menu item

In each Mac application there is a main menu item with the name of the application. Lazarus will automatically add the "Services", "Hide" and "Quit" menu items to this menu. In order to add more item to this menu, create a menu item with the apple character as its Caption "" (without quotes). You can use ifdefs {$IFNDEF DARWIN} to make it invisible in non-Mac OS X platforms.

See also

Links

Coming to OS X from Unix or Linux?

Coming to OS X from Windows and want to learn Unix scripting?

Coming to Object Pascal from C++, C# or Java?