# Rake help

**URL:** <https://rubytalk.org/t/rake-help/17262>\
**Category:** ruby-talk\
**Created:** [29 March 2005 22:11 UTC](https://rubytalk.org/t/rake-help/17262 "2005-03-29T22:11:05Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mark\_Probert](https://avatars.discourse-cdn.com/v4/letter/m/d2c977/32.png) [@Mark\_Probert](https://rubytalk.org/u/Mark_Probert)\
**Post date:** [29 March 2005 22:11 UTC](https://rubytalk.org/t/rake-help/17262/1 "2005-03-29T22:11:05Z")

</div>

Hi ..

I have just started using the excellent Rake tool (thanks, Jim!) and I am at a  
bit of a loss on how to proceed. I am attempting to create unit test for  
some C++ code I am creating, using the cxxtest tool.

cxxtest has its tests contained in a .h file. These are then parsed by the  
tool to give your .cpp file. This is then complied and linked with the  
object file.

So, assuming I have my code in foo.cpp, my tests in foo\_test.h, then the  
sequence looks like:

$ c++ -c -o foo.o foo.cpp  
$ [cxxtest.pl](http://cxxtest.pl) -o foo\_test.cpp foo\_test.h  
$ c++ -o foo\_test foo\_test.cpp foo.o

So, there are two issues that I am having problems with. The first is turning  
the .h into a .cpp.

The second is how to get the test to conditionally depend on foo.o. I only  
want to create foo.o if it isn't there. If it exists, then it will do for  
the build. In reality, there will be multiple classes in each .o file, yet a  
unit test per class.

Anyway, here is my rakefile, which isn't quite right. Giving:

$ rake  
c++ -o unittest unittest scanner.o  
c++: unittest: No such file or directory  
rake aborted!

Many thanks,  
-m.

# -!- Ruby -!-

> **···**
>
> #  
> # Rakefile for cocor\_cpp  
> #
> 
> LINK\_OBJ = "scanner.o"  
> task :default =\> [:unittest]
> 
> # --------  
> # Unit test harness for cocor  
> #  
> def ext(fn, newext)  
> &nbsp;&nbsp;&nbsp;&nbsp;fn.sub(/\.[^.]+$/, newext)  
> end
> 
> UT\_SRC = ["ts\_buffer.h"]  
> UT\_CPP = UT\_SRC.collect { |fn| ext(fn, ".cpp") }
> 
> UT\_CPP.each do |utcpp|  
> &nbsp;&nbsp;&nbsp;&nbsp;utsrc = ext(utcpp, ".h")  
> &nbsp;&nbsp;&nbsp;&nbsp;file utcpp =\> [utsrc] do |t|  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cxxopt = "--have-eh --error-printer"  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sh( "[cxxtestgen.pl](http://cxxtestgen.pl) #{cxxopt} -o #{utcpp} #{utsrc}" )  
> &nbsp;&nbsp;&nbsp;&nbsp;end  
> end
> 
> task :unittest =\> UT\_CPP do |t|  
> &nbsp;&nbsp;&nbsp;&nbsp;exe = File.basename([t.name](http://t.name), '.\*')  
> &nbsp;&nbsp;&nbsp;&nbsp;sh( "c++ -o #{exe} #{[t.name](http://t.name)} #{LINK\_OBJ}" )  
> end
> 
> --  
> -mark. (probertm at acm dot org)

---

<div class="post-metadata">

**Author:** ![Jim\_Weirich1](https://avatars.discourse-cdn.com/v4/letter/j/73ab20/32.png) [@Jim\_Weirich1](https://rubytalk.org/u/Jim_Weirich1)\
**Post date:** [31 March 2005 22:48 UTC](https://rubytalk.org/t/rake-help/17262/2 "2005-03-31T22:48:40Z")

</div>

Mark Probert said:

> I have just started using the excellent Rake tool (thanks, Jim!) and I am  
> at a  
> bit of a loss on how to proceed. I am attempting to create unit test for  
> some C++ code I am creating, using the cxxtest tool.

Hi Mark, Sorry it took me so long to respond to this. You probably have  
solved this already, but I'll post for the general education of all Rake  
Users everywhere (well, at least the ones on this list.

> cxxtest has its tests contained in a .h file. These are then parsed by  
> the tool to give your .cpp file. This is then complied and linked  
> with the object file.
> 
> So, assuming I have my code in foo.cpp, my tests in foo\_test.h, then the  
> sequence looks like:
> 
> $ c++ -c -o foo.o foo.cpp  
> $ cxxtest.pl -o foo\_test.cpp foo\_test.h  
> $ c++ -o foo\_test foo\_test.cpp foo.o

Ok, I'm going to work with this example rather than the Rakefile you  
posted below. There should be enough info to apply it to your rakefile.

> So, there are two issues that I am having problems with. The first is  
> turning the .h into a .cpp.

Not a problem ... You want to generate .cpp files from .h files with the  
same base name. The easiest way is to express this as an explicit file  
task:

&nbsp;&nbsp;file "foo\_test.cpp" =\> ["foo\_test.h"] do  
&nbsp;&nbsp;&nbsp;&nbsp;sh %{cxxtest.pl -o foo\_test.cpp foo\_test.h}  
&nbsp;&nbsp;end

The above says that file "foo\_test.cpp" depends on a header file named  
"foo\_test.h", and that to create the .cpp file, all you need to do is run  
the cxxtest.pl command with the given parameters.

Using the same logic, we can come up with tasks for the other two files as  
well:

&nbsp;&nbsp;file "foo.o" =\> ["foo.cpp"] do  
&nbsp;&nbsp;&nbsp;&nbsp;sh %{c++ -c -o foo.o foo.cpp}  
&nbsp;&nbsp;end

&nbsp;&nbsp;file "foo\_test" =\> ["foo\_test.cpp", "foo.o"] do  
&nbsp;&nbsp;&nbsp;&nbsp;sh %{c++ -o foo\_test foo\_test.cpp foo.o}  
&nbsp;&nbsp;end

Those three file tasks together in a rake file will build foo\_test  
whenever you type "rake foo\_test" at the command line. Supposedly you  
want to run the tests as well. Simply add

&nbsp;&nbsp;task :unittest =\> ["foo\_test"] do  
&nbsp;&nbsp;&nbsp;&nbsp;sh "foo\_test"  
&nbsp;&nbsp;end

And if you want that to be the default task, then add:

&nbsp;&nbsp;task :default =\> [:unittest]

Take all of the above together and you get a working Rakefile. Now lets  
fine tune it a bit.

First of all, the Rakefile is overly restrictive. Suppose you added  
"bar\_test.h" to the mix? You would have to add a task to build it and  
modify existing tasks to depend upon it. Fortunately, you are using Ruby,  
and you can create those tasks in a test...

&nbsp;&nbsp;FileList['\*\_test.h'].each do |source|  
&nbsp;&nbsp;&nbsp;&nbsp;target = source.sub(/\.h$/, '.cpp')  
&nbsp;&nbsp;&nbsp;&nbsp;file target =\> [fn] do  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sh "cxxtest.pl -o #{target} #{source}"  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

We are assuming that the test header files contain end in "\_test.h".  
Modify according to your needs.

If you have 20 test headers, the above code will create 20 explicit tasks  
for generating the test cpp files. This works great, however, there is  
another way ... rules.

&nbsp;&nbsp;rule '.cpp' =\> '.h' do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;sh "cxxtest.pl -o #{t.name} #{t.source}"  
&nbsp;&nbsp;end

This rule says that whenever you need a .cpp file, and you have a .h file  
with the same name, here's how you would generate the .cpp file. It is  
similar to generating the tasks explicitly (as we did in the loop above),  
but instead of generating the tasks all at once it only does it on an as  
needed basis.

In the same way, we can give a rule for compiling .cpp files into .o files.

&nbsp;&nbsp;rule '.o' =\> '.cpp' do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;sh "c++ -c -o #{t.name} #{t.source}"  
&nbsp;&nbsp;end

I also like to create a bunch of file lists that describe the categories  
of files. Here's what might work for you ...

CPP\_SOURCE = FileList['\*.cpp'].exclude('\*\_test.cpp')  
TEST\_HEADERS = FileList['\*\_test.h']

Now I want to combine these lists into a single list of all the object  
files I will be dealing with ...

&nbsp;&nbsp;OBJ = FileList[  
&nbsp;&nbsp;&nbsp;&nbsp;CPP\_SOURCE.sub(/\.cpp$/, '.o'),  
&nbsp;&nbsp;&nbsp;&nbsp;TEST\_HEADERS.sub(/\.h$/, '.o'),  
&nbsp;&nbsp;]

That leaves our final compile rule to look like this ...

&nbsp;&nbsp;file "foo\_test" =\> OBJ do  
&nbsp;&nbsp;&nbsp;&nbsp;sh "c++ -o foo\_test #{OBJ}"  
&nbsp;&nbsp;end

I'll show the complete Rakefile at the end and include some simple  
clean/clobber rules.

> The second is how to get the test to conditionally depend on foo.o. I  
> only want to create foo.o if it isn't there. [...]

Not a problem. Rake will only regenerate a file in a file task when the  
file is out of date w.r.t. its dependencies.

> Anyway, here is my rakefile, which isn't quite right. Giving:
> 
> $ rake  
> c++ -o unittest unittest scanner.o  
> c++: unittest: No such file or directory  
> rake aborted!

In your :unittest task, you are compiling and EXE, but give it t.name as  
the file to compile. Since the task name is :unittest, there is no file  
by that name.

Here's my Rakefile ...

> **···**
>
> ----------------------------------------------------  
> # -\*- ruby -\*-
> 
> require 'rake/clean'
> 
> CLEAN.include('\*.o')  
> CLOBBER.include('foo\_test', 'foo\_test.cpp')
> 
> CPP\_SOURCE = FileList['\*.cpp'].exclude(/test.cpp$/)  
> TEST\_HEADERS = FileList['\*\_test.h']  
> OBJ = FileList[  
> &nbsp;&nbsp;CPP\_SOURCE.sub(/\.cpp$/, '.o'),  
> &nbsp;&nbsp;TEST\_HEADERS.sub(/\.h$/, '.o'),  
> ]
> 
> task :default =\> :unittest
> 
> task :unittest =\> "foo\_test" do  
> &nbsp;&nbsp;sh "foo\_test"  
> end
> 
> file "foo\_test" =\> OBJ do  
> &nbsp;&nbsp;sh "c++ -o foo\_test #{OBJ}"  
> end
> 
> rule '.o' =\> '.cpp' do |t|  
> &nbsp;&nbsp;sh "c++ -c -o #{t.name} #{t.source}"  
> end
> 
> rule '.cpp' =\> '.h' do |t|  
> &nbsp;&nbsp;sh "cxxtest.pl -o #{t.name} #{t.source}"  
> end  
> ----------------------------------------------------
> 
> --  
> -- Jim Weirich jim@weirichhouse.org [http://onestepback.org](http://onestepback.org)  
> -----------------------------------------------------------------  
> "Beware of bugs in the above code; I have only proved it correct,  
> not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)

---

<div class="post-metadata">

**Author:** ![Sam\_Roberts1](https://avatars.discourse-cdn.com/v4/letter/s/ed8c4c/32.png) [@Sam\_Roberts1](https://rubytalk.org/u/Sam_Roberts1)\
**Post date:** [1 April 2005 00:01 UTC](https://rubytalk.org/t/rake-help/17262/3 "2005-04-01T00:01:42Z")

</div>

Quoting probertm@acm.org, on Wed, Mar 30, 2005 at 07:11:05AM +0900:

> I have just started using the excellent Rake tool (thanks, Jim!) and I am at a  
> bit of a loss on how to proceed. I am attempting to create unit test for  
> some C++ code I am creating, using the cxxtest tool.
> 
> cxxtest has its tests contained in a .h file. These are then parsed by the  
> tool to give your .cpp file. This is then complied and linked with the  
> object file.
> 
> So, assuming I have my code in foo.cpp, my tests in foo\_test.h, then the  
> sequence looks like:

This is a little off-topic, but you might find that GNU make has had a  
dozen years of optimization for doing this kind of stuff easily and  
concisely:

--- makefile ---  
default: test

TEST\_H = $(wildcard \*\_test.h)  
TEST\_E = $(TEST\_H:.h=)

exe: $(TEST\_E)

test: exe  
&nbsp;&nbsp;for t in $(TEST\_E); do ./$$t; done

%.o: %.cpp  
&nbsp;&nbsp;c++ -c -o $@ $\<

%\_test.cpp: %\_test.h  
&nbsp;&nbsp;cxxtest.pl -o $@ $\<

%\_test: %\_test.o %.o  
&nbsp;&nbsp;&nbsp;c++ -o $@ $^

> **···**
>
> ----------------
> 
> This makefile enforces your naming convention, that the unit test for  
> BAR are in BAR\_test.h, and the source is in BAR.cpp
> 
> I took the liberty of running the tests by default, as all good  
> makefiles should do.
> 
> Cheers,  
> Sam

---

<div class="post-metadata">

**Author:** ![Mark\_Probert](https://avatars.discourse-cdn.com/v4/letter/m/d2c977/32.png) [@Mark\_Probert](https://rubytalk.org/u/Mark_Probert)\
**Post date:** [31 March 2005 23:34 UTC](https://rubytalk.org/t/rake-help/17262/4 "2005-03-31T23:34:36Z")

</div>

Hi ..

Many thanks, Jim. First, Rake is excellent! There is one part of the  
scenario that I'd like to explore, and a comment.

> rule '.cpp' =\> '.h' do |t|  
> &nbsp;&nbsp;sh "cxxtest.pl -o #{t.name} #{t.source}"  
> end

I did get around to reading more of the documentation and have ended up using  
rules. My results where very similar to yours.

When I created th.h -\> .cpp rule, it would run against all .h files that it  
could find, rather than just the unit test ones. So I ended up with:

&nbsp;&nbsp;UT\_EXE = ["test1", "test2", "test3"] # all have a .h file defining tests

&nbsp;&nbsp;rule '.cpp' =\> ['.h'] do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;name = t.name.sub(/\.[^.]+$/, "")  
&nbsp;&nbsp;&nbsp;&nbsp;if UT\_EXE.include?(name)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sh( "#{CXXTEST} #{CXXTESTOPT} -o #{t.name} #{t.source}" )  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

I have also found that it is useful to have a dependency list for the various  
UTs, as not all of the UTs required all of the files of the application. So,  
something like the following works:

&nbsp;&nbsp;UT\_T1\_DEP = ["test1.cpp", "foo.o"]  
&nbsp;&nbsp;UT\_T2\_DEP = ["test2.cpp", "bar.o"]  
&nbsp;&nbsp;UT\_T3\_DEP = ["test3.cpp", "foo.o", "bar.o"]

My UT drivers look like:

&nbsp;&nbsp;file "test1" =\> UT\_T1\_DEP do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;sh( "#{CC} #{CCOPT} -o #{t.name} #{t.prerequisites.join(' ')}" )  
&nbsp;&nbsp;end

&nbsp;&nbsp;file "test2" =\> UT\_T2\_DEP do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;sh( "#{CC} #{CCOPT} -o #{t.name} #{t.prerequisites.join(' ')}" )  
&nbsp;&nbsp;end

&nbsp;&nbsp;file "test3" =\> UT\_T3\_DEP do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;sh( "#{CC} #{CCOPT} -o #{t.name} #{t.prerequisites.join(' ')}" )  
&nbsp;&nbsp;end

And the overall driver is a task:

&nbsp;&nbsp;task :testsuite =\> UT\_EXE do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;puts "--\> finished creating the tests"  
&nbsp;&nbsp;end

The first question: is there a way to factor the UT drivers into a rule? I  
can't seem to get the dependcies right.

Second: What is the best way of making this work in a sub-directory? Use  
explicit paths in the UT\_\*\_DEP lines to ensure the link is right? Have a  
Rakefile in the UT director driven by one in the main directory?

Again, many thanks for an excellent tool! I have been playing with Make and  
Jam for ages, and Rake has the potential to replace them all for me 🙂

Have you thought of doing the equivalent of Jambase and having a packaged  
library of default rules that will be applied, based on the platform that  
Rake is invoked on? So, if Linux, CC=gcc, if Win32 CC=cl, etc..

Regards,

> **···**
>
> On Thursday 31 March 2005 14:48, Jim Weirich wrote:
> 
> --  
> -mark. (probertm at acm dot org)

---

<div class="post-metadata">

**Author:** ![Jim\_Weirich1](https://avatars.discourse-cdn.com/v4/letter/j/73ab20/32.png) [@Jim\_Weirich1](https://rubytalk.org/u/Jim_Weirich1)\
**Post date:** [1 April 2005 13:18 UTC](https://rubytalk.org/t/rake-help/17262/5 "2005-04-01T13:18:26Z")

</div>

> I did get around to reading more of the documentation and have ended up  
> using rules. My results where very similar to yours.
> 
> When I created th.h -\> .cpp rule, it would run against all .h files that it  
> could find, rather than just the unit test ones. So I ended up with:

Rules can be based on more than just file extensions. The target can be a  
regular expression and the dependency can be an arbitrary lambda that does a  
transform. The following (untested) might work for you ...

rule(/^test\d+\.cpp$/, '.h') do |t|  
&nbsp;&nbsp;sh "#{CXXTEST} #{CXXTESTOPT} -o #{t.name} #{t.source}"  
end

> I have also found that it is useful to have a dependency list for the  
> various UTs, as not all of the UTs required all of the files of the  
> application. So, something like the following works:

Likewise, a pattern based rule might work here too (again, untested):

rule(/^test\d+$/, '.cpp') do |t|  
&nbsp;&nbsp;sh "#{CC} #{CCOPT} -o #{t.name} #{t.prerequisites.join(' ')}"  
end

And then the dependencies can be given explicitly.

file "test1" =\> ["test1.cpp", "foo.o"]  
file "test2" =\> ["test2.cpp", "bar.o"]  
file "test3" =\> ["test3.cpp", "foo.o", "bar.o"]

This become really powerful when you can write a little ruby to scan your  
source for #includes and generate the dependencies automatically.

Hmmm ... now that I look at the above, I'm wondering if the explicit  
dependencies will prevent the rules from triggering. Try it and let me know  
if it doesn't work here.

> The first question: is there a way to factor the UT drivers into a rule?  
> I can't seem to get the dependcies right.

> Second: What is the best way of making this work in a sub-directory? Use  
> explicit paths in the UT\_\*\_DEP lines to ensure the link is right? Have a  
> Rakefile in the UT director driven by one in the main directory?

I'm not a big fan of having one Rakefile invoke a Rakefile in a subdirectory.  
I would rather see one Rakefile control the whole process. (You can get  
finer grain dependencies that way). An alternative would be to place  
Rakefile fragments in the directories and have a main rakefile load them.  
The downside to this is that there is no namespaces in the Rakefile, all  
tasks exist at a single global level, so there would need to be some  
coordination between the subdirectories.

> Have you thought of doing the equivalent of Jambase and having a packaged  
> library of default rules that will be applied, based on the platform that  
> Rake is invoked on? So, if Linux, CC=gcc, if Win32 CC=cl, etc..

Yep. I'm thinking through some ways of making namespaces work with Rake tasks  
and how library modules might fit into this. When RubyGems slows down a bit,  
I plan to revisit Rake and do something along the lines that you suggest.

Thanks for the feedback.

> **···**
>
> On Thursday 31 March 2005 06:34 pm, Mark Probert wrote:
> 
> --  
> -- Jim Weirich jim@weirichhouse.org [http://onestepback.org](http://onestepback.org)  
> -----------------------------------------------------------------  
> "Beware of bugs in the above code; I have only proved it correct,  
> not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)

---

<div class="post-metadata">

**Author:** ![Mark\_Probert](https://avatars.discourse-cdn.com/v4/letter/m/d2c977/32.png) [@Mark\_Probert](https://rubytalk.org/u/Mark_Probert)\
**Post date:** [2 April 2005 00:45 UTC](https://rubytalk.org/t/rake-help/17262/6 "2005-04-02T00:45:33Z")

</div>

Hi ..

> Likewise, a pattern based rule might work here too (again, untested):
> 
> rule(/^test\d+$/, '.cpp') do |t|  
> &nbsp;&nbsp;sh "#{CC} #{CCOPT} -o #{t.name} #{t.prerequisites.join(' ')}"  
> end

Works well. My rule looks like:

&nbsp;&nbsp;rule( '.exe' =\> [  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;proc {|tn| tn.sub(/\.[^.]+$/, '.cpp').insert(0, "#{UT\_DIR}\/") }  
&nbsp;&nbsp;&nbsp;&nbsp;]) do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;bn = t.name.sub("\.exe", "")  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;objlist = check\_dep(UT\_DIR + "/" + bn + ".h")  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sh( "#{CC} #{CCOPT} -o #{UT\_DIR}/#{bn} #{t.prerequisites.join(' ')} \  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#{objlist}" )  
&nbsp;&nbsp;end

So, I use a synthetic target and use the check\_dep() call to extract the  
dependent .o file from the #include (thanks for the tip 🙂 ).

> And then the dependencies can be given explicitly.
> 
> file "test1" =\> ["test1.cpp", "foo.o"]

This also works, though I don't think that I have dependencies are quite  
right.

In order to get things to work correctly, I have created a synthetic target  
that enables an extension rule to be triggered. So:

&nbsp;&nbsp;file "ut\_buffer" =\> ["scanner.o", "ut\_buffer.exe",] do |t|  
&nbsp;&nbsp;&nbsp;&nbsp;puts " .. running tests --\> #{t.name}"  
&nbsp;&nbsp;&nbsp;&nbsp;sh( "#{UT\_DIR}/#{t.name}" )  
&nbsp;&nbsp;end

So, this works well, though I would like not to have to specify the ".o"  
dependency on the UT driver line. I assume that the way to do this is to add  
the check\_dep() to the proc and join the list to the prerequisites?

Regards,

> **···**
>
> On Friday 01 April 2005 05:18, Jim Weirich wrote:
> 
> --  
> -mark. (probertm at acm dot org)
