Generating a Makefile from Xcode

Generating a Makefile from Xcode

Almost all open source software projects I have encountered rely on GNU Make as a build tool. Make is a tool available on many platforms (most notably Linux and UNIX) that manages the compilation and installation of software programs. A Makefile defines the location of source files and steps required to compile and link targets to create the executable program file.

Importing existing Make-based software projects into Apple’s Xcode IDE is relatively easy; source files can be dragged and dropped into a Project, and Xcode will link and compile them automatically.

Unfortunately, porting Xcode Projects to other platforms is not so simple. While Xcode can integrate a Makefile as an External Build Target, it cannot export or create one. This functionality is granted with the use of a third party tool called PBTOMAKE. Note that Xcode was originally called Project Builder.

PBTOMAKE is a command line utility which creates a simple Makefile from an Xcode Project file. Integrating PBTOMAKE into an Xcode Project allows us to create a Makefile on the fly as part of the build process. Here’s how:

  1. Download and install PBTOMAKE, so that the ‘pbtomake’ command is available to the current user.
  2. In Xcode, ensure all Project file reference paths are specified Relative to the Project.
  3. Right click on the relevant build Target, and add a New Run Script Build Phase. Enter the following command:

    pbtomake -i $PROJECT_NAME.xcodeproj -o path/to/Makefile

  4. Build your Project.

PBTOMAKE’s default compiler is GCC. Use the -cc option to change compiler, and -bin_dir to specify an alternate output directory.

An example cross-platform command-line application written in C++ which links against OpenSSL‘s libraries would use the following Run Script Build Phase to generate a Makefile from within Xcode:

pbtomake -i $PROJECT_NAME.xcodeproj -o path/to/Makefile -link_opt "-lssl -lcrypto" -no_framework -cc g++ -bin_dir path/to/bin

This method allows us to create and maintain C and C++ projects in Xcode, while providing excellent cross-platform portability via GNU Make.