[Rant-cafe] Build C/C++ code

Peter Allin pal at foss.dk
Wed Apr 23 15:56:32 EDT 2008


> Can't anyone give me an example of rant recepie to compile hog.S into hog.o
> with gcc? I know command: "gcc -I. -o hog.o hog.S", but Rant syntax with all
> generators is confusing while examples from documentation does not work.

If you just want to create a rule for translating a single .c file
into a .o file, the following should do it:

  file "bar.o" => "bar.c" do
    sys "gcc -c -I. -o bar.o bar.c"
  end

This tells rant that the file "bar.o" depends on "bar.c", and that it
should run the given command line to create "bar.o". This means that
the command will be run when the date of "bar.c" is newer than the
date of "bar.o" or when "bar.o does not exist.

But you will probably quickly tire of writing a rule for each .o file
in your program. the "Rule" generator can help you out like this:

  gen Rule, '.o' => '.c' do |t|
    sys "gcc -c -I. -o #{t.name} #{t.source}"
  end

The first line says that we want a rule for creating ".o" files from
".c" files. The 't' variable passed to the block is a an object of the
FileTask class, which amongst others defines these methods:

 - prerequisites, which returns a list of the file names of the
   prerequisites for the task.

 - source, which returns the name of the first prerequisite for the
   class.

 - name, which returns the name of the file that should be generated
   by the task.

The second line then use the "name" and "source" methods to generate a
command line and run it with the "sys" method.

If you want the ".o" files linked into an executable, add something
like this to your Rantfile:

  file "myprog" => [ "bar.o", "foo.o", "main.o"] do |t|
    sys "gcc #{t.prerequisites.join ' '} -o myprog"  
  end

This will make the "myprog" file depend on the three ".o" files in the
list, and execute a command line linking all the prerequisites.

With a little more complexity you can make the files be rebuilt
whenever the commandline use to create them changes (for example when
you change compiler options). The code below will do that:

  import "command"
   
  gen Command, "myprog" => [ "bar.o", "foo.o", "main.o"] do |t|
    "gcc #{t.prerequisites.join ' '} -o myprog"  
  end
   
  gen Rule, '.o' => '.c' do |target, sources|
    gen Command, target => sources  do |t|
      "gcc -c -I. -o #{t.name} #{t.source}"
    end
  end


All the examples above compiles from ".c" files, but it should be simple to add ".S" files using the same techniques.


I hope this can be of some help,
 Peter Allin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://rubyforge.org/pipermail/rant-cafe/attachments/20080423/d834f409/attachment.html 


More information about the Rant-cafe mailing list