Using Apple's Xcode with makefiles

Building with makefiles

Most of the projects I am involved with use the make utility for compiling (GNU Make). A version of make is installed by Apple's Xcode Tools package.

In the case of older fortran programs that are normally compiled directly from the command line, you can create a simple makefile as follows:

# Targets

all: HelloFortran

HelloFortran: hello.f
    /sw/bin/g77 -g -o Hello hello.f

clean:
    rm Hello

To test your makefile, type make at the command line. The -g flag causes the compiler to include debug symbols. When building final (release) versions of your program, you should remove -g and replace it with one of the optimization flags, such as -O2.

Using the GNU Make target in Xcode

Once you have a working makefile, you can create an Xcode project as follows:

  1. Choose File -> New Project, and select "GNU Make" from the list of possible project types. Set the project name and directory and click Finish. (Note that the "GNU Make" option is not available on older versions of Xcode - I suggest updating to the latest version as described on my OS X Notes page.)

  2. Click Project -> Add To Project, and select your source code files.

  3. The makefile target should be automatically created. You can examine the settings by clicking on the target in the Groups & Files window on the left-hand side of Xcode. To build the target, just click the Build button. If the build was successful, you should be able to run the executable from the command line.

  4. To run the debugger in Xcode, you need to create a custom executable in the Groups & Files window. Crtl-click the executables icon, choose Add -> New Custom Executable, and fill in the Executable Path. To debug, select Debugger from the Debug drop-down menu, and click on Debug in the Debugger. You can view the console output by clicking the Console button. You can set breakpoints by clicking in the left margin in your source-code files.

Note to fortran users: I have not been able to get the debugger to work properly with breakpoints when working with fortran projects. I get gdb errors right after the program halts at a breakpoint. gdb works fine when debugging the same executable from the command line, so I'm not sure what the problem is in Xcode. If anyone figures this out, please let me know.