guiadeprogramacaognulinux

27
8/3/2019 GuiadeProgramacaoGNUlinux http://slidepdf.com/reader/full/guiadeprogramacaognulinux 1/27 Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA Guia de Programação em GNU/Linux Autor: Ademar de Souza Reis Júnior [email protected] Agosto de 2000 Guia de Programação em GNU/Linux www.cipsga.org.br − [email protected] Página 1  Erro de leitura

Upload: jonas-miranda

Post on 07-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 1/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Guia deProgramaçãoem GNU/Linux

Autor: Ademar de Souza Reis Júnior

[email protected]

Agosto de 2000

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 1

 

Erro de leitura

Page 2: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 2/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Guia de Programação em GNU/Linux

Versão 1.1

Comite de Incentivo a Produçãodo Software Gratuito e Alternativo

CIPSGA

Autor:

 Ademar de Souza Reis [email protected]@ademar.org

Agosto de 2000 

Diagramação e ArteCIPSGA

Copyright (c) 2000, Ademar de Souza Reis Junior.Permission is granted to copy, distribute and/or modify this document under the terms of the GNU FreeDocumentation License, Version 1.1 or any later version published by the Free Software Foundation; with theInvariant Sections being LIST THEIR TITLES, with the Front−Cover Texts being LIST, and with the Back−Cover Texts being LIST.

A copy of the license is included in the section entitled "GNU Free Documentation License".

Copyright (c) 2000, Ademar de Souza Reis JuniorE garantida a permissão para copiar, distribuir e/ou modificar este documento sob os termos da GNU Free Documentation License,

versão 1.1 ou qualquer outra versão posterior publicada pela Free Software Foundation; sem obrigatoriedade de Seções Invariantes naabertura e ao final dos textos.

Uma copia da licença deve ser incluída na seção intitulada GNU Free Documentation License.

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 2

 

Page 3: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 3/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Índice

INTRODUÇÃO.................................................................................................................................4

O QUE VOCÊ PRECISA PARA CRIAR UM PROGRAMA................................................................5

1 − EDITOR DE TEXTOS 52 − COMPILADOR 5

3 − DEPURADOR 6

4 − OUTROS 6

OS UTILITÁRIOS........................................................................................... ..................................7

GCC − O COMPILADOR C....................................................................... .......................................7

GDB − DEPURADOR C/C++............................................................................................................8

MAKE.............................................................................................................................................16

CONCLUSÃO.................................................................................................................................19

FUTURAS ATUALIZAÇÕES............................................ ................................................. .............19

SOBRE O AUTOR 20

CONTROLE DE VERSÕES 21

GNU FREE DOCUMENTATION LICENSE.......................................... ...........................................22

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 3

 

Page 4: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 4/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Introdução

Este documento visa passar algumas explicações sobre a programação em ambiente linux. Ele é voltado paraestudantes e programadores que queiram programar nesse ambiente. Isso requer o conhecimento dealgumas características do sistema e o aprendizado de alguns utilitários.

Para a leitura desse documento, você deve ter um pequeno conhecimento prévio do sistema de arquivos dolinux, sua estrutura de diretórios e usuários, além de uma certa familiaridade com a sintaxe de comandos.Você também deve saber consultar uma página manual e documentação info. Assumimos ainda que vocêsabe utilizar um editor de textos simples, como o vi ou o emacs e, obviamente, ter conhecimentos deprogramação (os exemplos estão em C).

Se você ainda não se sente familiar com o sistema linux, é recomendado que, antes mesmo de continuar aleitura desse texto, você consulte outras fontes de documentação introdutória.

Primeiramente vamos nos lembrar que o ato de programar consiste−se (do ponto de vista prático),basicamente em:

1. Escrever o código;

2. Compilar o código;

3. Depurar o código;

Sendo que a segunda etapa pode ser um pouco extendida ao se programar com vários módulos e/oubibliotecas.

Pra quem está acostumado a programar em outros ambientes, como em MS−DOS, essas etapas geralmeneestão agrupadas em uma IDE (Interface de Desenvolvimento), como o Borland C.

Mas quando programamos em linux, geralmente utilizamos um utilitário para cada etapa. Isso apresentaalgumas vantagens como flexibilidade, pois podemos utilizar nossos programas favoritos ou disponíveis paracumprir cada tarefa.

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 4

 

Page 5: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 5/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

O que você precisa para criar um

programaEmbora existam IDE’s disponíveis para o ambiente do linux, a maioria dos programadores optam por trabalharindependentemente, escolhendo suas ferramentas favoritas.

Seguindo o raciocínio visto para as etapas da programação, precisamos dominar os seguintes tipos deutilitários:

1 − Editor de textos

Existem vários editores disponíveis no ambiente linux. Alguns apresentam funcionalidades extras paraprogramadores (como identação automática, sintaxe colorida, verificação de erros na sintaxe, etc).

Os dois editores mais utilizados são o vim (VI Improved) e o emacs, mas você deve utilizar o editor de suapreferência.

2 − Compilador

A tarefa do compilador é a mais importante. Existem compiladores para as mais diversas linguagens no linux.Obviamente, você deve escolher aquele que melhor suprir suas necessidades.

Os dois compiladores mais utilizados são o gcc e o g++ (respectivamente, GNU C Compiler e GNU C++

Compiler).

É importante você conhecer as flags de compilação de cada um e as opções mais usadas.

As flags mais importantes são:

− Warnings

Elas lhe ajudam a encontrar falhas na sintaxe e lógica do programa, que não impedem a compilação domesmo.

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 5

 

Page 6: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 6/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Indispensável principalmente se você programa em C, pois esta linguagem é bastante flexível no que dizrespeito à compilação, e permite que um código muito mal escrito seja compilado sem apresentar erros.

− Otimização

Permitem que o compilador utilize instruções otimizadas ou específicas de um determinado processador.

Para descobrir quais as flags de seu compilador, consulte sua documentação.

3 − Depurador

Esse é o utilitário que você utilizará quando as coisas não funcionam da primeira vez, ou seja, sempre... :)

O depurador mais utilizado no ambiente linux é o gdb (GNU DeBuguer). Ele é um poderoso e excelentedepurador para as linguagens C e C++.

4 − Outros

Existem diversos outros utilitários que auxiliam muito o programador no ambiente linux.

Um dos mais indispensáveis e úteis é o make. Ele permite otimizar e automatizar várias etapas dacompilação, facilitando muito essa tarefa.

Além deste, existem também bibliotecas para depuração, utilitários gráficos, utilitários para layout, patchs, etc.

Abaixo uma lista do que você pode achar interessante: (procure documentação a respeito nas páginasmanuais)

make

EletricFence

checker

indent

diff

patch

autoconf

cvs

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 6

 

Page 7: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 7/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Resumindo, você precisa dominar pelo menos quatro utilitário no total: Editor de textos, make, compilador edepurador. Mas não pense que isso faz do linux um ambiente difícil para a programação. Como foi citado àpouco, existem IDE’s muito práticas no linux... Mas como quase toda a interface, elas são apenas "frontends"para os utilitários citados.

Os utilitáriosVeremos de forma mais detalhada os utilitários mais importantes citados acima.

Como já foi dito, você deve utilizar o editor de textos que você mais gosta e onde você se sinta confortávelpara digitar o código, portanto, a escolha e o aprendizado ficam por sua conta.

gcc − O Compilador CSem dúvida o compilador mais utilizado e importante dos sistemas Unix. Embora existam outros compiladorespara a linguagem C disponíveis, o gcc é, de longe, o mais famoso e completo. Ele foi criado e mantido pelacomunidade GNU, e está em estágio de ser considerado um dos melhores compiladores existentes para alinguagem C.

Após criar um arquivo com o código corretamente escrito, você deve utilizar o gcc da seguinte forma:

$ gcc fonte.c

O resultado é a criação de um arquivo executavel de nome "a.out" que é resultado da compilação do códigocontido no arquivo "fonte.c"

Se você quer que o gcc crie um arquivo executável com um nome específico (e geralmente você quer), vocêdeve utilizar a opção (que chamaremos de "flag") "−o", que significa "outupt" (saída). Ela é utilizada antes donome do arquivo que será criado.

Abaixo refaremos a compilação do exemplo anterior, mas criando um arquivo de nome "executavel":

$ gcc fonte.c −o executavel

Para compilar programas que estejam em vários arquivos, você deve primeiramente compilar os móduloscomo objetos para então compilar o programa principal.

Vamos ver como exemplo o caso da compilação de um programa que esteja separado em três partes(arquivos):

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 7

 

Page 8: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 8/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

interface.c

processamento.c

principal.c

A sequencia para a criação de nosso programa, que chamaremos de "teste" seria:

$ gcc −c inteface.c −o interface.o

$ gcc −c processamento.c −o processamento.o

$ gcc interface.o processamento.o principal.c −o teste

A flag "−o" já é por nós conhecida. A novidade fica por conta da flag "−c" (compilar mas não linkar) que éutilizada para a criação do arquivo objeto.

Esse processo se torna cansativo e demais trabalhoso para ser feito sem uma automação. Para essa tarefaveremos o utilitário "make" mais adiante.

Outras flags bastante importantes são as de "warnings" (alertas). São elas que vão detectar problemas emnosso código que vão desde falta de estilo até problemas com passagem de parâmetros e, principalmente,ponteiros.

As mais utilizadas e por mim recomendadas são:

−pedantic −Wall −W −Wtraditional −Wshadow −Wpointer−arith

−Wbad−function−cast −Wcast−qual −Wcast−align −Wwrite−strings −Wconversion

−Waggregate−return −Wmissing−prototypes −Wmissing−declarations

−Wnested−externs −Winline −Wwrite−strings

A explicação de cada uma dessas opções é muito extensa para ser explicada aqui. Para isso é altamenterecomendado que você faça uma consulta à documentação do gcc (páginas manuais e info).

Obviamente, algumas dessas opções podem se tornar incômodas na criação de programas que, por ummotivo ou outro, precisam quebrar certas "regras" para chegar a algum resultado. Aliás, essa é uma dasmaiores características da linguagem C: flexibilidade.

gdb − Depurador C/C++Existem vários depuradores disponíveis para o ambiente do linux, mas o mais utilizado e suportado comcerteza é o gdb. Como o gcc, ele foi criado e é mantido pela comunidade GNU, e apresentando um ambientesimples mas recursos bastante avançados, é considerado um dos melhores depuradores existentes para o

ambiente Unix (sendo então usado por muitos frontends).

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 8

 

Page 9: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 9/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Nosso objetivo é conferir a utilização básica do gdb. Uma documentação mais completa você encontra nadocumentação própria.

Executar o gdb é simples. Primeiramente, você deve compilar seu programa (e módulos objeto) com a flag −g

ou uma das equivalentes, que incluirá no programa executável informações necessárias à depuração.

Ao executar o gdb, é bom que você tenha acesso ao código fonte de seu programa para ir conferindo aexecução.

Você deve executar o gdb como abaixo:

$ gdb arquivo_executável

A interface do gdb é simples:

GNU gdb 4.17.0.12 with Linux support

Copyright 1998 Free Software Foundation, Inc.

GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/ordistribute copies of it under certain conditions.

Type "show copying" to see the conditions.

There is absolutely no warranty for GDB. Type "show warranty" for details.

This GDB was configured as "i386−Debian/GNU−linux"...

(gdb)

Agora você só precisa utilizar os comandos necessários para acompanhar a execução do código,depurando−o.

A técnica básica para depuração é:

− Inserir um breakpoint no ponto onde você deseja iniciar a depuração (linha N do código);

− Executar o programa (dentro do gdb);

− Avançar na execução, conferindo os parâmetros passados às funções e o

tipo e conteúdo das variáveis.

A sintaxe dos comandos é simples: você tem o comando por extenso e o comando simplificado (geralmente aprimeira letra do mesmo). Os parâmetros (como números de linha e nomes de variáveis) são passadosimediatamente após o comando.

Os comandos mais importantes são:

Inserir breakpoint na linha N:

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 9

 

Page 10: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 10/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

break N

b N

Remover todos os breakpoints:

deleted

Rodar o programa até o primeiro breakpoint ou fim do mesmo:

run <parametros>

r <parametros>

onde <parametros> sao os argumentos passados ao programa (como uma flag ou nome de arquivo)

Executar proximas N linhas:

next N

n N

Executar proximas N passos:

step N

s N

Matar (encerrar) o programa:

kill

k

Exibir informacoes sobre o tipo de uma variavel:

what <nome_var>

w <nome_var>

Exibir o conteúdo de uma variavel:

print <nome_var>

p <nome_var>

Visualizar pilha de recursao:

backtrace

bt

Obter ajuda em relação a algum comando:

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 10

 

Page 11: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 11/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

help <comando>

h <comando>

Sair do gdb:quit

q

A sintaxe em relação às variáveis é a utilizada na linguagem C.

O último comando pode ser repetido pressionando−se [ENTER].

Vamos agora conferir um exemplo bem simples em linguagem C: (se você tiver dificuldades em entender o

código, então você precisa estudar um pouco mais de C) :)

O programa a seguir tem como único objetivo o aprendizado do gdb. Ele não tem nenhuma utilidade, sentidoou objetivo lógico.

−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−

#include <stdlib.h>

#include <stdio.h>

#define MAGICO 16

void funcao1(char **c);

int funcao2(int x);

int main (void)

{

int a = 100;

char b;char *c;

c = (char *) malloc(sizeof(char) * (MAGICO));

funcao1(&c);

a = funcao2(a);

 

printf("%s\n", c);

 

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 11

 

Page 12: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 12/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

exit(0);

}

void funcao1(char **c)

{int i;

for (i = 0; i < MAGICO; i++)

*c[i] = ’a’;

}

int funcao2(int x)

{

return x * MAGICO + 50;

}

−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−

$ gcc exemplo.c −o exemplo −g

$ ./exemplo

Segmentation fault (core dumped)

A mensagem acima nos diz que o programa foi interrompido pelo kernel por tentar acessar uma área inválidada memória ou executar uma instrução não acessível.

Vamos agora à depuração no gdb:

$ gdb exemplo

GNU gdb 4.17.0.12 with Linux support

Copyright 1998 Free Software Foundation, Inc.

GDB is free software, covered by the GNU General Public License, and you arewelcome to change it and/or distribute copies of it under certain conditions.

Type "show copying" to see the conditions.

There is absolutely no warranty for GDB. Type "show warranty" for details.

This GDB was configured as "i386−Debian GNU/Linux"...

Core was generated by ‘./exemplo’.

Program terminated with signal 11, Segmentation fault.

#0 0x80484b0 in funcao1 (c=0xbffff3bc) at exemplo.c:30

30 *c[i] = ’a’;

(gdb) print i

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 12

 

Page 13: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 13/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

$1 = 4

(gdb)

Como você pode ver, o gdb, a partir do arquivo de core gerado juntamento com o segmentation fault, jádetecta em que linha ocorreu o erro, e você pode executar comandos como "print i". Isso muitas vezes já é o

suficiente. Mas vamos executar o programa passo a passo assim mesmo:

(gdb) b 10

Breakpoint 1 at 0x8048430: file exemplo.c, line 10.

(gdb) r

Starting program: /home/ademar/prog/exemplo

Breakpoint 1, main () at exemplo.c:10

10 {

(gdb) next

main () at exemplo.c:11

11 int a = 100;

(gdb) next

15 c = (char *) malloc(sizeof(char) * (MAGICO + 1));

(gdb) next

17 funcao1(&c);

(gdb) stepfuncao1 (c=0xbffff39c) at exemplo.c:29

29 for (i = 0; i < MAGICO; i++)

(gdb) print *c

$2 = 0x8049640 ""

(gdb) next

30 *c[i] = ’a’;

(gdb) print i

$4 = 0(gdb) next 8

30 *c[i] = ’a’;

(gdb) print i

$15 = 4

(gdb) print *c

$18 = 0x8049640 "a"

Ops. Tem coisa errada aqui. O comando print seguido de uma variável que seja um vetor de caracteres

(string), imprime todo o seu conteúdo, desde o primeiro caracter até o ’\0’. O que vemos aqui é que o vetortem apenas um caracter.

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 13

 

Page 14: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 14/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Pensando um pouco, conseguimos notar que estamos acessando o vetor de maneira errada. O correto seria(*c)[i], e não *c[i].

Problema resolvido. :)

Agora vamos executar o programa (corrigido) até seu término dentro do gdb, utilizando os comandossimplificados (apenas a primeira letra):

$ gcc exemplo.c −o exemplo −g

$ ./exemplo

aaaaaaaaaaaaaaaa

A linha cima é o resultado de nosso programa em execução. Útil, não? :)

$ gdb exemplo

[...]

(gdb) b 10

Breakpoint 1 at 0x8048430: file exemplo.c, line 10.

(gdb) r

Starting program: /home/ademar/prog/exemplo

Breakpoint 1, main () at exemplo.c:1010 {

(gdb) n

main () at exemplo.c:11

11 int a = 100;

(gdb) n

15 c = (char *) malloc(sizeof(char) * (MAGICO + 1));

(gdb) n

17 funcao1(&c);(gdb) s

funcao1 (c=0xbffff39c) at exemplo.c:29

29 for (i = 0; i < MAGICO; i++)

(gdb) n

30 (*c)[i] = ’a’;

(gdb) n 30

30 (*c)[i] = ’a’;

(gdb) p i

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 14

 

Page 15: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 15/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

$1 = 15

(gdb) p *c

$2 = 0x8049640 ’a’ <repeats 15 times>

Agora sim. O vetor "c" contém 15 vezes a letra ’a’.

(gdb) n

29 for (i = 0; i < MAGICO; i++)

(gdb) n

31 }

(gdb) n

main () at exemplo.c:18

18 a = funcao2(a);

(gdb) p a

$3 = 100

(gdb) n

20 printf("%s\n", c);

(gdb) p a

$4 = 1650

(gdb) n

aaaaaaaaaaaaaaaa22 exit(0);

(gdb) n

Program exited normally.

(gdb)

Esse é o fim da execução.

Este exemplo é bastante simples, mas se você teve dificuldades em acompanhar, crie um programa aindamais simples (hello word) e faça os testes. Você verá grande utilidade no gdb principalmente quando estivertrabalhando com estruturas e ponteiros, pois com variáveis desse tipo é praticamente impossível a depuraçãousando−se "printf’s".

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 15

 

Page 16: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 16/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

make

A utilização do make é bastante simples e prática. O make é extremamente útil quando estamos trabalhandoem um projeto grande (com vários módulos a compilar) ou quando usamos várias opções de compilação − oque, como vimos acima, é indispensável.

Basicamente, o make é um "automatizador" de comandos. Ele pode ser utilizado para agrupar um conjunto decomandos qualquer em um "rótulo" que chamamos logo após o comando "make".

Para utilizar o make, você deve criar um arquivo com os rótulos e os comandos que o make deve executar.Esse arquivo deve chamar−se Makefile ou makefile (o formato e utilização dos arquivos é a mesma, equando precisar−mos citá−los, vamos citar apenas como "Makefile").

O formato de um arquivo Makefile simples é o seguinte:

# comentário

rótulo: dependências

<TABULACAO>comando1; \ 

comando2; \ 

...; \ 

comandon;

Onde:

# comentário

É um texto ignorado, serve para documentar o arquivo.

rótulo

Em compilações, deve ser o nome do arquivo resultante da utilização dos comandos (geralmente resultadoda compilação)

dependências

Nome dos arquivos e/ou rótulos que devem ser verificados antes da execução dos comandos (vejaexplicação abaixo)

<TABULACAO>

É uma tabulação comum. Não deve conter espaços, apenas uma tabulação.

O principal erro ao criar−se um arquivo Makefile reside aqui...

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 16

 

Page 17: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 17/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

comandos

A lista de comandos que devem ser executados pelo make para o respectivo rótulo. Ao final de cada linha,deve−se inserir uma barra inversa "\", para continuar a lista (ou até mesmo um comando único) na linha logoabaixo.

É comum especificarmos algumas "variáveis" locais ao arquivo do make para facilitar a sintaxe, deixando−amais simples. A utilização de variáveis é similar à maneira como usamos na shell bash, como mostradoabaixo:

Atribuição:

VARIAVEL=valor

Utilização:

$VARIAVEL

Uma das grandes vantagens em se utilizar o make é a verificação das dependências. O funcionamento ésimples: antes de executar os comandos de um determinado rótulo, o make verifica se os rótulos listados nalista de dependências já foram executados. Para isso, ele verifica se o arquivo rótulo (que, como citadoacima, deve ser o nome do arquivo resultante da compilação) é mais recente que suas dependências.

Essa é uma forma de evitar a recompilação de módulos que não precisem ser recompilados, e sempre deveser usada, pois otimiza em muito esse processo.

Abaixo temos um exemplo de arquivo Makefile comentado, que tem como objetivo criar um programa de

nome teste, utilizando uma série de flags e opções para o gcc (através da utilização de variáveis).

# Compilador usado (C Compiler)

CC=gcc

# Opcoes diversas para o gcc

# Para uma explicação detalhada sobre a utilidade de cada opção, veja a

# documentação do gcc (man / info)

OVERALL_OPTIONS=−pipe

DIALECT_OPTIONS=−ansi

# Destaque para as opções de warning abaixo. Elas são extremamente úteis na

# detecção de erros.

WARN_OPTIONS=−pedantic −Wall −W −Wtraditional −Wshadow −Wpointer−arith\ 

−Wbad−function−cast −Wcast−qual −Wcast−align −Wwrite−strings\ 

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 17

 

Page 18: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 18/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

−Wconversion −Waggregate−return\ 

−Wmissing−prototypes −Wmissing−declarations\ 

−Wnested−externs −Winline −Wwrite−strings

DEBUG_OPTIONS=−g

LDFLAGS=−lm

# junta todas as opções de compilação em uma variavel só (CFLAGS)

CFLAGS=$(OVERALL_OPTIONS) $(DIALECT_OPTIONS) $(WARN_OPTIONS) $(DEBUG_OPTIONS)\ 

$(CODE_GENERATION_OPTIONS)

# all − usado pra simplificar, permitindo o uso do comando make sem nenhum

# parâmetro (rótulo)

all: teste

# programa principal

teste: modulo.o teste.c

$CC teste.c modulo.o −o teste $(CFLAGS)

# compilacao de um modulomodulo.o: modulo.c

$CC −c modulo.c −o modulo.o $(CFLAGS)

# excluir tudo o que foi compilado

clean:

rm *.o teste −f

Como sempre, vale a pena conferir a documentação relativa ao make.

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 18

 

Page 19: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 19/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Conclusão

Programar em linux exige um pouco de conhecimento e aprendizado, mas vale a pena, principalmente sevocê pretende realmente entender o que está acontecendo a cada passo.

Futuras atualizações− Melhores exemplos

− diff e patch

− IDE’s

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 19

 

Page 20: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 20/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Sobre o autor

Aguardando texto do autor...

Ademar de Souza Reis Jr. <[email protected]>

Estudante de Informática e Bolsista PET − UFPR

http://www.ademar.org/ 

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 20

 

Page 21: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 21/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Controle de versões

Data Autor Observações  07/08/2000 Ademar de Souza Reis

JuniorVersão inicial − 1.1

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 21

 

Page 22: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 22/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

GNU Free Documentation LicenseVersion 1.1, March 2000

Copyright (C) 2000 Free Software Foundation, Inc.

59 Temple Place, Suite 330, Boston, MA 02111−1307 USAEveryone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.

0. PREAMBLEThe purpose of this License is to make a manual, textbook, or other written document "free" in the sense offreedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it,either commercially or noncommercially. Secondarily, this License preserves for the author and publisher away to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of "copyleft", which means that derivative works of the document must themselves befree in the same sense. It complements the GNU General Public License, which is a copyleft license designedfor free software.

We have designed this License in order to use it for manuals for free software, because freesoftware needs free documentation: a free program should come with manuals providing the same freedomsthat the software does. But this License is not limited to software manuals; it can be used for any textual work,regardless of subject matter or whether it is published as a printed book. We recommend this Licenseprincipally for works whose purpose is instruction or reference.

1. APPLICABILITY AND DEFINITIONSThis License applies to any manual or other work that contains a notice placed by the copyright holder saying itcan be distributed under the terms of this License. The "Document", below, refers to any such manual or work.Any member of the public is a licensee, and is addressed as "you".

A "Modified Version" of the Document means any work containing the Document or a portion of it, eithercopied verbatim, or with modifications and/or translated into another language.

A "Secondary Section" is a named appendix or a front−matter section of the Document that deals exclusivelywith the relationship of the publishers or authors of the Document to the Document’s overall subject (or torelated matters) and contains nothing that could fall directly within that overall subject. (For example, if theDocument is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) Therelationship could be a matter of historical connection with the subject or with related matters, or of legal,commercial, philosophical, ethical or political position regarding them.

The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those ofInvariant Sections, in the notice that says that the Document is released under this License.

The "Cover Texts" are certain short passages of text that are listed, as Front−Cover Texts orBack−Cover Texts, in the notice that says that the Document is released under this License.

A "Transparent" copy of the Document means a machine−readable copy, represented in a format whosespecification is available to the general public, whose contents can be viewed and edited directly andstraightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (fordrawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatictranslation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparentfile format whose markup has been designed to thwart or discourage subsequent modification by readers is notTransparent. A copy that is not "Transparent" is called "Opaque".

Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format,LaTeX input format, SGML or XML using a publicly available DTD, and

standard−conforming simple HTML designed for human modification. Opaque formats include PostScript,PDF, proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 22

 

Page 23: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 23/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

which the DTD and/or processing tools are not generally available, and the machine−generated HTMLproduced by some word processors for output purposes only.

The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed tohold, legibly, the material this License requires to appear in the title page.For works in formats which do not have any title page as such, "Title Page" means the text near the most

prominent appearance of the work’s title, preceding the beginning of the body of the text.2. VERBATIM COPYINGYou may copy and distribute the Document in any medium, either commercially or noncommercially, providedthat this License, the copyright notices, and the license notice saying this License applies to the Document arereproduced in all copies, and that you add no other conditions whatsoever to those of this License. You maynot use technical measures to obstruct or control the reading or further copying of the copies you make ordistribute. However, you may accept compensation in exchange for copies. If you distribute a large enoughnumber of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.

3. COPYING IN QUANTITY

If you publish printed copies of the Document numbering more than 100, and the Document’s license noticerequires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these CoverTexts: Front−Cover Texts on the front cover, and Back−Cover Texts on the back cover. Both covers must alsoclearly and legibly identify you as the publisher of these copies. The front cover must present the full title withall words of the title equally prominent and visible. You may add other material on the covers in addition.Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfythese conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (asmany as fit reasonably) on the actual cover, and continue the rest ontoadjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include

a machine−readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy apublicly−accessible computer−network location containing a complete Transparent copy of the Document, freeof added material, which the general network−using public has access to download anonymously at no chargeusing public−standard network protocols. If you use the latter option, you must take reasonably prudent steps,when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thusaccessible at the stated location until at least one year after the last time you distribute an Opaque copy(directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing anylarge number of copies, to give them a chance to provide you with an updated version of the Document.

4. MODIFICATIONSYou may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3

above, provided that you release the Modified Version under precisely this License, with the Modified Versionfilling the role of the Document, thus licensing distribution and modification of the Modified Version to whoeverpossesses a copy of it. In addition, you must do these things in the Modified Version:

A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from thoseof previous versions (which should, if there were any, be listed in the History section of the Document).You may use the same title as a previous version if the original publisher of that version gives permission.

B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of themodifications in the Modified Version, together with at least five of the principal authors of the Document(all of its principal authors, if it has less than five).

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 23

 

Page 24: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 24/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

C. State on the Title page the name of the publisher of the Modified Version, as the publisher.

D. Preserve all the copyright notices of the Document.

E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.

F. Include, immediately after the copyright notices, a license notice giving the public permission to use theModified Version under the terms of this License, in the form shown in the Addendum below.

G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in theDocument’s license notice.

H. Include an unaltered copy of this License.

I. Preserve the section entitled "History", and its title, and add to it an item stating at least the title, year, newauthors, and publisher of the Modified Version as given on the Title Page. If there is no section entitled"History" in the Document, create one stating the title, year, authors, and publisher of the Document asgiven on its Title Page, then add an item describing the Modified Version as stated in the previous

sentence.J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the

Document, and likewise the network locations given in the Document for previous versions it was basedon. These may be placed in the "History" section. You may omit a network location for a work that waspublished at least four years before the Document itself, or if the original publisher of the version it refers togives permission.

K. In any section entitled "Acknowledgements" or "Dedications", preserve the section’s title, and preserve inthe section all the substance and tone of each of the contributor acknowledgements and/or dedicationsgiven therein.

L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section

numbers or the equivalent are not considered part of the section titles.

M. Delete any section entitled "Endorsements". Such a section may not be included in the Modified Version.

N. N. Do not retitle any existing section as "Endorsements" or to conflict in title with any Invariant Section.

O. If the Modified Version includes new front−matter sections or appendices that qualify as SecondarySections and contain no material copied from the Document, you may at your option designate some or allof these sections as invariant. To do this, add their titles to the list of Invariant Sections in the ModifiedVersion’s license notice. These titles must be distinct from any other section titles.

You may add a section entitled "Endorsements", provided it contains nothing but endorsements of yourModified Version by various parties−−for example, statements of peer review or that the text has been

approved by an organization as the authoritative definition of a standard.

You may add a passage of up to five words as a Front−Cover Text, and a passage of up to 25 words as aBack−Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front−Cover Text and one of Back−Cover Text may be added by (or through arrangements made by) any one entity.If the Document already includes a cover text for the same cover, previously added by you or by arrangementmade by the same entity you are acting on behalf of, you may not add another; but you may replace the oldone, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names forpublicity for or to assert or imply endorsement of any Modified Version.

5. COMBINING DOCUMENTS

You may combine the Document with other documents released under this License, under the terms defined insection 4 above for modified versions, provided that you include in the combination all of the Invariant Sections

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 24

 

Page 25: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 25/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in itslicense notice.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections maybe replaced with a single copy. If there are multiple Invariant Sections with the same name but differentcontents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the

original author or publisher of that section if known, or else a unique number. Make the same adjustment to thesection titles in the list of Invariant Sections in the license notice of the combined work.

In the combination, you must combine any sections entitled "History" in the various original documents, formingone section entitled "History"; likewise combine any sections entitled "Acknowledgements", and any sectionsentitled "Dedications". You must delete all sections entitled "Endorsements."

6. COLLECTIONS OF DOCUMENTSYou may make a collection consisting of the Document and other documents released under this License, andreplace the individual copies of this License in the various documents with a single copy that is included in thecollection, provided that you follow the rules of this License for verbatim copying of each of the documents inall other respects.

You may extract a single document from such a collection, and distribute it individually under this License,provided you insert a copy of this License into the extracted document, and follow this License in all otherrespects regarding verbatim copying of that document.

7. AGGREGATION WITH INDEPENDENT WORKSA compilation of the Document or its derivatives with other separate and independent documents or works, inor on a volume of a storage or distribution medium, does not as a whole count as a Modified Version of theDocument, provided no compilation copyright is claimed for the compilation. Such a compilation is called an"aggregate", and this this License does not apply to the other self−contained works thus compiled with theDocument, on account of their being thus compiled, if they are not themselves derivative works of theDocument. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if theDocument is less than one quarter of the entire aggregate, the Document’s Cover Texts may be placed oncovers that surround only the Document within the aggregate. Otherwise they must appear on covers around

the whole aggregate.

8. TRANSLATIONTranslation is considered a kind of modification, so you may distribute translations of the Document under theterms of section 4. Replacing Invariant Sections with translations requires especial permission from theircopyright holders, but you may include translations of some or all Invariant Sections in addition to the originalversions of these Invariant Sections. You may include a translation of this License provided that you alsoinclude the original English version of this License. In case of a disagreement between the translation and theoriginal English version of this License, the original English version will prevail.

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 25

 

Page 26: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 26/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

9. TERMINATIONYou may not copy, modify, sublicense, or distribute the Document except as expressly provided for under thisLicense. Any other attempt to copy, modify, sublicense or distribute the Document is void, and willautomatically terminate your rights under this License. However, parties who have received copies, or rights,from you under this License will not have their licenses terminated so long as such parties remain in full

compliance.10. FUTURE REVISIONS OF THIS LICENSEThe Free Software Foundation may publish new, revised versions of the GNU Free Documentation Licensefrom time to time. Such new versions will be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns. See http://www.gnu.org/copyleft/.

Each version of the License is given a distinguishing version number. If the Document specifies that aparticular numbered version of this License "or any later version" applies to it, you have the option of followingthe terms and conditions either of that specified version or of any later version that has been published (not asa draft) by the Free Software Foundation. If the Document does not specify a version number of this License,you may choose any version ever published (not as a draft) by the Free Software Foundation.

How to use this License for your documents.To use this License in a document you have written, include a copy of the License in the document and put thefollowing copyright and license notices just after the title page:

Copyright (c) YEAR YOUR NAME.Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.1or any later version published by the Free Software Foundation;with the Invariant Sections being LIST THEIR TITLES, with theFront−Cover Texts being LIST, and with the Back−Cover Texts being LIST.A copy of the license is included in the section entitled "GNU

Free Documentation License".

If you have no Invariant Sections, write "with no Invariant Sections" instead of saying whichones are invariant. If you have no Front−Cover Texts, write "no Front−Cover Texts" instead of "Front−CoverTexts being LIST"; likewise for Back−Cover Texts.

If your document contains nontrivial examples of program code, we recommend releasing these examples inparallel under your choice of free software license, such as the GNU General Public License, to permit theiruse in free software. 

Guia de Programação em GNU/Linux − www.cipsga.org.br − [email protected] − Página 26

 

Page 27: GuiadeProgramacaoGNUlinux

8/3/2019 GuiadeProgramacaoGNUlinux

http://slidepdf.com/reader/full/guiadeprogramacaognulinux 27/27

Comitê de Incentivo a Produção do Software Gratuito e Alternativo – CIPSGA

Comitê de Incentivo a Produção do

Software Gratuito e Alternativo

Fundado em 29 de janeiro de 1999.

1ª Diretoria

Djalma Valois FilhoDiretor Executivo

[email protected]

José Luiz Nunes Poyares Paulo Roberto Ribeiro GuimarãesDiretor Administrativo Diretor Institucional

CIPSGARua Professora Ester de Melo, numero 202,

Parte, Benfica, Rio de Janeiro, RJ, CEP. 20930−010;Telefone (Fax/Dados): 021−5564201;e−mail: [email protected]

CNPJ: 03179614−0001/70