Xcode: Running a script before every build that modifies source code directly

Every technique mentioned so far is an overkill. Reproducing steve kim's comment for visibility:

In the build phases tab, simply drag the "Run Script" step to a higher location (e.g. before "Compile Sources").

Tested on Xcode 6


This solution is probably outdated. See the higher voted answer instead; I no longer actively use Xcode and am not qualified to vet a solution.


Use "External Target":

  1. Select "Project" > "New Target..." from the menu
  2. Select "Mac OS X" > "Other" > "External Target" and add it to your project
  3. Open its settings and fill in your script setup
  4. Open the "General" tab of the main target's settings and add the new target as it's direct dependency

Now the new "External Target" runs before the main target even starts gathering dependency information, so that any changes made during the script execution should be included in the build.


There is another, slightly simpler option that doesn't require a separate target, but it's only viable if your script tends to modify the same source files every time.

First, here's a brief explanation for anyone who's confused about why Xcode sometimes requires you to build twice (or do a clean build) to see certain changes reflected in your target app. Xcode compiles a source file if the object file it produces is missing, or if the object file's last-modified date is earlier than the source file's last-modified date was at the beginning of the first build phase. If your project runs a script that modifies a source file in a pre-compilation build phase, Xcode won't notice that the source file's last-modified date has changed, so it won't bother to recompile it. It's only when you build the project a second time that Xcode will notice the date change and recompile the file.

Here's a simple solution if your script happens to modify the same source files every time. Just add a Run Script build phase at the end of your build process like this:

touch Classes/FirstModifiedFile.m Classes/SecondModifiedFile.m
exit $?

Running touch on these source files at the end of your build process guarantees that they will always have a later last-modified date than their object files, so Xcode will recompile them every time.