因为学习C#各种特性和使用方法的需要,常常会编写和收集一些例子代码。一段时间之后,这种代码的数量就增加到无法通过简单粗暴的方式进行管理了。采用NAnt进行管理是一个不错的选择,虽然部分特性只有MSBuild才支持,基于偏好选择NAnt。
首先是一个顶层目录下的配置文件。
<?xml version="1.0"?> <project name="hycs project" default="build"> <target name="*"> <nant target="${target::get-current-target()}"> <buildfiles> <include name="**/*.build" /> <!-- avoid recursive execution of current build file --> <exclude name="${project::get-buildfile-path()}" /> </buildfiles> </nant> </target> </project>
这个文件的功能就是提供搜索子目录下的build配置文件,并根据命令行指定的目标来执行操作。为了避免出现死循环,加上了 exclude 命令。
对于诸多小文件的目录,采用每个源码文件编译成一个可执行程序的策略。最开始没有采用通配的方法,直接针对每个文件写命令。
<?xml version="1.0"?> <project name="Math" default="run"> <property name="debug" value="true" /> <target name="clean" description="remove all generated files"> <!-- Files: '*.xml; *.pdb' --> <delete> <fileset> <include name="*.xml" /> <include name="*.exe" /> </fileset> </delete> <delete file="oledb.exe" /> </target> <target name="build" description="compiles the source code"> <csc debug="${debug}" output="helloMath.exe" target="exe" win32icon="..ico riple.ico"> <sources> <include name="helloMath.cs" /> </sources> </csc> </target> <target name="run" depends="build"> <exec program="helloMath.exe" /> </target> </project>
文件数量增加后,写命令的工作量就变得惊人了。想想办法,如何才能多快好省呢?
<?xml version="1.0"?> <project name="xml" default="run"> <property name="debug" value="true" /> <target name="clean" description="remove all generated files"> <!-- Files: '*.xml; *.pdb' --> <delete> <fileset> <include name="*.xml" /> <include name="*.exe" /> <include name="*.pdb" /> </fileset> </delete> </target> <target name="build" description="compiles the source code"> <foreach item="File" property="filename"> <in> <items> <include name="*.cs" /> </items> </in> <do> <echo message="${filename}" /> <csc debug="${debug}" output="${path::change-extension(filename, 'exe')}" target="exe"> <sources> <include name="${filename}" /> </sources> </csc> </do> </foreach> </target> <target name="run" depends="build"> <foreach item="File" property="filename"> <in> <items> <include name="*.exe" /> </items> </in> <do> <echo message="${filename}" /> <exec program="${filename}" /> </do> </foreach> </target> </project>
现在每个文件都能进行编译了。就算增加更多的文件,也不需要修改配置文件。暂时就到这里,之后还会遇到其他的问题,比如DLL如何处理,C/C++代码如何处理,第三方库文件如何处理等等,待有时间慢慢道来。