Pages

Friday, October 21, 2011

Uma visão básica e essencial sobre Autotools - Parte I


O que é o Autotools?

O Autotools ou, como também é chamado, GNU build system é comumentemente utilizado por desenvolvedores de software livre para tornar seu programa bastante portável e, principalmente, para prover uma automatização ao projeto.
Com o GNU Make já é possível obter uma automatização sensível na elaboração e construção de qualquer projeto, entretanto, quando usamos o GNU Automake até o próprio arquivo de Makefile é gerado automaticamente, ou seja, não é mais necessário gastar tempo na codificação de um arquivo Makefile, por exemplo.
A Ferramenta GNU Autoconf é mais interessante ainda. Com ela é possível gerar scripts que configuram seu projeto de forma automática, adaptando-o ao sistema que está sendo usado e verificando as dependências necessárias.


Colocando a mão na massa!

Neste post, abordaremos uma visão simples e fácil para utilizarmos o Autotools em nossos projetos.

Antes de iniciar, devemos baixar os pacotes essenciais. Com um simples apt-get (para sistemas Debian-like) resolvemos o problema.

$ sudo apt-get install autoconf automake

Depois de instalados, podemos iniciar a automatização de nosso projeto com um "Hello World!" básico a seguir,

// helloworld.c
#include <stdio.h>

int main(int argc, char *argv[]) {

printf("Hello world!\n");

return 0;
}

Para dificultar colocaremos o código-fonte em uma pasta chamada "src" e na pasta base criaremos o makefile a seguir,

#makefile

all:
gcc -o helloworld src/helloworld.c

clean:
rm -r -f helloworld *.o src/*.o

Portanto, já temos nosso código base na pasta "src" e o makefile na pasta raiz. Agora iniciaremos o uso do GNU Autotools. Para isso, realizaremos todas as operações na pasta raiz (onde se encontra o makefile). Portanto, no shell devemos efetuar primeiramente,

$ autoscan

Gerando dois arquivos: o autoscan.log e o configure.scan. Devemos renomear esse útlimo para que ele sirva como entrada para geração do script de configuração pelo comando autoconf.

$ mv configure.scan configure.ac

e por fim,

$ autoconf

Notemos que foi criado um script chamado "configure" e uma pasta chamada "autom4te.cache". Veremos mais a frente o porquê esta pasta é necessária.

Antes de executarmos nosso script devemos renomear o nosso makefile para "makefile.in". Afinal, ele será um input para o script gerar o makefile.

mv makefile makefile.in

Já podemos então executar o script configure.

./configure

A saída esperada será:

checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
configure: creating ./config.status
config.status: creating makefile
config.status: error: cannot find input file: `config.h.in'

Notemos que ele não achou o arquivo de entrada "config.h.in", porém ele gerou o makefile.
Logo, podemos executar esse script em qualquer máquina para gerar o makefile automaticamente, verificando as dependências.

Agora basta um simples comando make para compilar e gerar o binário desejado.

Por fim, chegamos aos primeiros passos da utilização do GNU Autotools, mais a frente iremos aprender novos conceitos, inserir bibliotecas e gerar um makefile a partir do Automake.


Referências

Algumas Referências interessantes sobre Autotools:

http://www.lrde.epita.fr/~adl/autotools.html
http://markuskimius.wikidot.com/programming:tut:autotools

Tuesday, August 23, 2011

How to Develop a Cairo Clock using Common Lisp and GTK+

A Short Introduction

In my last project based on Lisp and GTK+ Toolkit, I need to use some graphics to build a drawing module. Then, the best solution found was the use of cairo libraries to render this kind of graphics. The Cairo API provides anti-aliasing and a simple handling.  However, I didn't find some books or tutorials that show how I could do it. With some searchs at Google, I found a tutorial made by the author of the Cairo bindings for Common Lisp, but the article didn't show an Cairo integration with Gtk+.

Then, in our laboratory, we understood the source code of the Cairo bindings for Lisp and built a solution to implement a application Lisp based, using Gtk+ and Cairo.

If you interested yourself or only want to learn the Common Lisp Language, I suggest the on-line book: "Practical Common Lisp". A suggestions for people who want to start programming Lisp is download, or a Eclipse plug-in called Cusp, or use Emacs running Slime. You can install the essentials packages using the command line,

$ sudo apt-get install emacs23 sbcl slime cl-alexandria cl-asdf cl-babel cl-cffi cl-closer-mop cl-clg cl-trivial-features cl-swank

The source packages of cl-cairo2 can be found at Cliki cl-cairo2 project. The installation is so easy, you need to extract the source and paste it in ~/.sbcl/site/. After create the symbolic links of all .asd,

$ ln -s ~/.sbcl/site/YOUR_CAIRO_FOLDER/*.asd ~/.sbcl/systems

Now, you're ready to start developing common lisp, gtk+ and cairo applications.


Developing Lisp Apps using Cairo and Gtk+

First you need to import the libraries using Asdf,

(asdf:load-system :cl-gtk2-gtk)
(asdf:load-system :cl-cairo2)
(asdf:load-system :cl-cairo2-x11)

The assignment of cairo context can be made with,

...
(let ((cr (make-instance 'cl-cairo2:context
                     :pointer cr-p
                     :width draw-w
                     :height draw-h
                     :pixel-based-p t)))
             (setq cl-cairo2:*context* cr)
             (cl-cairo2:rectangle 0 0 500 500 cr)
             (cl-cairo2:clip cr)
             (draw-clock cr)))))
...

The function that draws the cairo clock is,

;; Function to create the clock from a Cairo context
(defun draw-clock (context)
   (setq radius 180)
   (cl-cairo2:set-source-rgb 1 1 1 context)
   (cl-cairo2:arc (/ draw-h 2) (/ draw-w 2) (/ radius 2) 0 (* 2 pi) context)
   (cl-cairo2:fill-path context)
   (cl-cairo2:set-source-rgb 0 0 0 context)
   (cl-cairo2:arc (/ draw-h 2) (/ draw-w 2) (/ radius 2) 0 (* 2 pi) context)
   (cl-cairo2:stroke context)

   ;; 0 to 11 hours
   (loop for i from 1 to 12 do
          ...
   )
)

Then, we finished an example of using Cairo and Gtk on Lisp.
You can download the source code here: cairoclock.lisp