8 June 2007

Nant: Compiling Your Applications

by mo

I’ve been spending some time trying to learn how to create builds using nAnt. You can use a special nAnt element to compile your .cs source files against the C# compiler.

<target name="compile">
  <csc target="library" output="build\${project::get-name()}.dll" debug="${debug}">
      <include name="src\app\**\*.cs" />
      <exclude name="src\app\**\AssemblyInfo.cs" />

The above target will compile all .cs files into a single assembly called <PROJECT_NAME>.dll. (You specify your project name in the name attribute of the project element.)

<project name="LogMyTime">

The compile target will recurse through all the files in a subdirectory called “src” and compile all the files with a .cs extension into the final assembly, excluding the AssemblyInfo.cs file (If you have multiple projects, each one will most likely have a different AssemblyInfo.cs file containing assembly info for that project.) The target will try to save the assembly to a folder called “build”.

Before compiling you should ensure that the build folder exists. To do this you could create another nAnt target that creates the build directory. Here is an example.

<target name="init">
  <mkdir dir="build" />

We could now create a dependency between the compile target and the init target so that, the init target always runs before attempting to compile by adding the “depends” attribute.

  <target name="compile" depends="init"> ... </target>

Now we can run our nAnt task from the commandline:

The output will tell us what nAnt targets ran and if there were any compilation warnings or errors:

Related Resources: