ASLab Development Manual

Transcripción

ASLab Development Manual
Autonomous Systems Laboratory
aslab.org
c 2006 aslab
Title
ASLab Development Manual
Processes and Toolchains
Author
Reference
Release
Date
Address
Ricardo Sanz, Adolfo Hernando, Adolfo Yela, Carlos
Hernández
R-2006-005
2.0 Draft
17-04-2008
Autonomous Systems Laboratory
UPM - ETS Ingenieros Industriales
José Gutierrez Abascal 2
28006 Madrid
SPAIN
ASLab Development Manual
ASLab R-2006-005 v 2.0 Draft of 17-04-2008
Abstract
This report describes the ASLab development environment and provides guidelines concering the use of the different toolchains and appropriate programming
and coding techniques.
Keywords
ASLab, development, toolchain, programming, code.
Acknowledgements
We acknowledge the work of so many people that have produced the tools that we
use, both open source or commercial.
Table of Contents
I
Overall issues
1
Introduction
13
1.1
Document Objetives . . . . . . . . . . . . . . . . . . . . . . . .
13
1.2
Document Structure . . . . . . . . . . . . . . . . . . . . . . . .
13
1.3
Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14
1.4
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14
2
Development environment vision and rationale
15
3
Tool domains for hosts and targets
16
4
The software process detailed
17
5
CASE Tools
18
5.1
Upper CASE Tools . . . . . . . . . . . . . . . . . . . . . . . . .
18
5.1.1
Definition . . . . . . . . . . . . . . . . . . . . . . . . . .
18
5.1.2
Classification of CASE Tools . . . . . . . . . . . . . . .
18
Lower CASE Tools . . . . . . . . . . . . . . . . . . . . . . . . .
19
5.2
6
II
11
Platforms: Hosts and Targets
20
6.1
Host Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . .
20
6.2
Target Platforms . . . . . . . . . . . . . . . . . . . . . . . . . .
20
Basic Processes
7
21
Modeling
23
7.1
On Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
23
7.2
UML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
23
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
5 of 171
7.2.1
8
References . . . . . . . . . . . . . . . . . . . . . . . . . .
23
7.3
SysML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
24
7.4
ASLab Modeling Guideline . . . . . . . . . . . . . . . . . . . .
24
7.4.1
24
Programming
25
8.1
Coding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
25
8.1.1
Coding Layout and Style . . . . . . . . . . . . . . . . .
25
8.1.2
Formatting Suggestions . . . . . . . . . . . . . . . . . .
26
8.1.3
Comments . . . . . . . . . . . . . . . . . . . . . . . . . .
27
Programación en C/C++ con Linux . . . . . . . . . . . . . . . .
27
8.2.1
Conceptos fundamentales . . . . . . . . . . . . . . . . .
27
8.2.2
El ejemplo ”Hola mundo” . . . . . . . . . . . . . . . . .
28
8.2.3
Opciones del compilador gcc . . . . . . . . . . . . . . .
29
8.2.4
Make y los Makefiles . . . . . . . . . . . . . . . . . .
30
8.2
9
Documentation
43
9.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
43
9.2
Documenting Hardware . . . . . . . . . . . . . . . . . . . . . .
43
9.3
Documenting Software . . . . . . . . . . . . . . . . . . . . . . .
43
9.3.1
Self-Documenting Code: Comments . . . . . . . . . . .
43
9.3.2
External Documentation . . . . . . . . . . . . . . . . . .
45
Doxygen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
45
9.4.1
Information in the index page . . . . . . . . . . . . . . .
46
9.4.2
Special documentation blocks . . . . . . . . . . . . . . .
46
9.4.3
Putting documentation after members . . . . . . . . . .
53
9.4.4
Documentation at other places . . . . . . . . . . . . . .
54
9.4.5
Special documentation blocks in Python . . . . . . . . .
57
9.4
III
Modeling Tools . . . . . . . . . . . . . . . . . . . . . . .
10 Testing
59
Toolset
60
11 RSD and Eclipse
11.1 Why this is the most important chapter of the manual . . . . .
6 of 171
62
62
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
11.2 RSD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
62
11.3 Using CVS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
62
11.4 Using RSD as an UML modeling platform . . . . . . . . . . . .
63
11.5 Using RSD as a SysML modeling platform . . . . . . . . . . . .
63
11.6 Using Eclipse as a LaTeX environment . . . . . . . . . . . . . .
63
12 CVS
65
12.1 Tool domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
65
12.2 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
65
12.2.1 Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . .
65
12.2.2 Audience . . . . . . . . . . . . . . . . . . . . . . . . . .
66
12.2.3 Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . .
66
12.2.4 A Bit of CVS Terminology . . . . . . . . . . . . . . . . .
66
12.3 Introduction to CVS . . . . . . . . . . . . . . . . . . . . . . . . .
66
12.3.1 What is CVS for? . . . . . . . . . . . . . . . . . . . . . .
66
12.3.2 How to use CVS – First Sketch . . . . . . . . . . . . . .
66
12.4 The ASLab CVS Repository . . . . . . . . . . . . . . . . . . . .
82
12.4.1 Location of the ASLab CVS Repository . . . . . . . . .
82
12.4.2 Use Politics . . . . . . . . . . . . . . . . . . . . . . . . .
82
12.4.3 Directory structure of ASLab CVS repository . . . . . .
82
12.4.4 Using the ASLab CVS Repository . . . . . . . . . . . .
83
12.5 Using CVS with an Eclipse Based Tool . . . . . . . . . . . . . .
83
12.6 CVS with RSD or Eclipse . . . . . . . . . . . . . . . . . . . . . .
83
12.6.1 CVS configuration . . . . . . . . . . . . . . . . . . . . .
83
12.6.2 Sharing your projects . . . . . . . . . . . . . . . . . . . .
85
12.6.3 Working with projects from the repository . . . . . . .
88
12.7 Other reference material . . . . . . . . . . . . . . . . . . . . . .
91
12.7.1 Base documentation . . . . . . . . . . . . . . . . . . . .
91
12.7.2 Other CVS Links . . . . . . . . . . . . . . . . . . . . . .
91
12.8 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
91
13 WindRiver Workbench
92
13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
92
13.1.1 Wind River Workbench . . . . . . . . . . . . . . . . . .
92
13.1.2 Wind River Linux . . . . . . . . . . . . . . . . . . . . . .
92
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
7 of 171
13.1.3 Installation in a host system . . . . . . . . . . . . . . . .
93
13.1.4 Installation in a target system . . . . . . . . . . . . . . .
93
13.2 WindRiver Linux BSP for GENE-6330 . . . . . . . . . . . . . .
94
13.2.1 BSP (Board Support Package): tm crusoe . . . . . . . .
94
13.2.2 RPMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
94
13.3 WindRiver Linux BSP for Vaio TX2HP . . . . . . . . . . . . . .
96
13.3.1 BSP (Board Support Package): vaio tx2 . . . . . . . . .
96
13.3.2 RPMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
96
14 GCC
14.1 CPP - The Preprocessor
98
. . . . . . . . . . . . . . . . . . . . . .
98
14.2 GCC - Compiling C . . . . . . . . . . . . . . . . . . . . . . . . .
102
14.3 G++ - Compiling C++ . . . . . . . . . . . . . . . . . . . . . . .
106
14.4 GNAT - Compiling Ada . . . . . . . . . . . . . . . . . . . . . .
110
14.5 GFORTRAN - Compiling Fortran . . . . . . . . . . . . . . . . .
110
14.6 GCJ - Compiling Java . . . . . . . . . . . . . . . . . . . . . . . .
113
15 Java Development Kit
15.1 Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
118
15.2 Programas del JDK . . . . . . . . . . . . . . . . . . . . . . . . .
118
15.3 Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
120
15.4 An example that better demonstrates object-oriented programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
121
15.5 Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
121
15.6 Swing Application . . . . . . . . . . . . . . . . . . . . . . . . .
122
16 Object Request Brokers
8 of 171
118
123
16.1 TAO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
123
16.1.1 Documents about TAO . . . . . . . . . . . . . . . . . . .
123
16.1.2 Building ACE and TAO . . . . . . . . . . . . . . . . . .
125
16.2 MICO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
125
16.3 eORB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
126
16.4 OpenORB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
126
16.5 ICa and ICa ORB . . . . . . . . . . . . . . . . . . . . . . . . . .
126
16.5.1 Preparing files . . . . . . . . . . . . . . . . . . . . . . . .
126
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
16.5.2 Editing system files . . . . . . . . . . . . . . . . . . . . .
127
16.5.3 Environment variables . . . . . . . . . . . . . . . . . . .
127
17 Micro CCM
IV
V
129
ASLab Platforms
130
18 ASLab’s Host Platforms
132
19 ASLab’s Target Platforms
133
19.1 PCT Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . .
133
19.2 RCT Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . .
133
19.2.1 Higgs . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
133
19.2.2 Khepera . . . . . . . . . . . . . . . . . . . . . . . . . . .
133
Appendixes
134
A KDevelop
136
B
A.1 ¿Qué es KDevelop? . . . . . . . . . . . . . . . . . . . . . . . . .
136
A.2 Arrancando KDevelop por primera vez . . . . . . . . . . . . .
136
A.3 Los proyectos . . . . . . . . . . . . . . . . . . . . . . . . . . . .
139
A.4 El primer programa en KDevelop . . . . . . . . . . . . . . . . .
140
Rational Software Architect
151
B.1 Notes about Rational Software Architect 6.0 in Linux . . . . .
151
B.2 Notes about Rational Software Architect 7.0 in Linux . . . . .
153
C Using RSA and CVS
156
C.1 Before you begin: Installing and configuring software . . . . .
156
C.1.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . .
156
C.1.2 CVS repository assumptions . . . . . . . . . . . . . . .
156
C.1.3 Configuring RSA/eclipse workspace . . . . . . . . . .
156
C.2 Sharing a modeling project . . . . . . . . . . . . . . . . . . . . .
157
C.2.1 Starting Rational Software Architect . . . . . . . . . . .
157
C.2.2 Importing an existing modeling project . . . . . . . . .
157
C.2.3 Sharing a project . . . . . . . . . . . . . . . . . . . . . .
158
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
9 of 171
C.2.4 Adding to the modeling project . . . . . . . . . . . . . .
158
C.2.5 Committing your work to the repository . . . . . . . .
159
C.2.6 Developing models as part of a team . . . . . . . . . . .
160
C.2.7 Setting up work areas for the developers . . . . . . . .
160
C.2.8 Adding to the modeling project . . . . . . . . . . . . . .
161
C.2.9 Committing your work to the repository . . . . . . . .
161
C.2.10 Updating the work area for dev1 . . . . . . . . . . . . .
162
C.2.11 Starting parallel development: Comparing and merging models . . . . . . . . . . . . . . . . . . . . . . . . . .
162
C.3 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
165
C.3.1 Learn . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
165
C.3.2 Get products and technologies . . . . . . . . . . . . . .
166
D Target Platforms
10 of 171
167
D.1 Targets supported by GCC . . . . . . . . . . . . . . . . . . . . .
167
D.2 Standard C Library . . . . . . . . . . . . . . . . . . . . . . . . .
168
D.2.1 Targets supported by GNU C Library . . . . . . . . . .
168
D.2.2 dietlibc . . . . . . . . . . . . . . . . . . . . . . . . . . . .
169
D.2.3 Newlib (requires MMU) . . . . . . . . . . . . . . . . . .
169
D.2.4 UClibc (MMU-less) . . . . . . . . . . . . . . . . . . . . .
170
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Part I
O VERALL ISSUES
Chapter 1
Introduction
1.1
Document Objetives
The purpose of this document is to provide detailed information on development practices and tools of the ASLab research group. It is intended to
provide both:
• a handful user guide to start your development work at ASLab
• a detailed manual about our development practices and tools.
1.2
Document Structure
The structure of this document is as follows:
Part I: Overall issues This part of the document explain how to use this manual, and some general issues about system development and the
Chapter1: This chapter provides a brief overview of the document, it
structure and the writing conventions used.
Chapter2: Development environment vision and rationale
Chapter3: Tool domains for hosts and targets
Chapter4: The software process detailed
Chapter5: UpperCASE Tools
Chapter??: LowerCASE Tools
Chapter18: Host Platforms
ChapterD: Target Platforms
Part II: Basic processes This part is one of the most important in the ADM:
it is guideline of the common practices at ASLab for each stage in the
development process.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
13 of 171
Chapter7: Modeling
Chapter8: Programming
Chapter10: Testing
Chapter??: Documentation
Part III: Toolset This is probably the most important part of the document
for a rookie: it is a brief tutorial of each of the tools used at ASLab. It is
specially important chapter 11
Chapter11: Rational System Developer and Eclipse
Chapter12: CVS
Chapter13: WindRiver Workbench
Chapter14: GCC
Chapter15: Java Development Kit
Chapter16: Object Request Brokers
Chapter17: Component Platforms
Part III: Appendices Here there is a mixture of mostly deprecated things but
that can accidentally be useful.
1.3
Conventions
!!
1.4
This is not a rule, it is more than that, this is how
things are done at ASLab
References
See the ASLab Procedures Manual for detailed explanations on common administrative and operational tasks including those related with configurationof workstations.
14 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 2
Development environment vision and
rationale
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
15 of 171
Chapter 3
Tool domains for hosts and targets
16 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 4
The software process detailed
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
17 of 171
Chapter 5
CASE Tools
5.1
Upper CASE Tools
5.1.1
Definition
CASE (Computer Assisted Software/System Engineering) refers to the methods dedicated to an engineering discipline for the development of information systems together with automated tools that can be used in this process.
CASE can be decsribed as harboring two key ideas:
1. Computer Assistance in software development and/or maintainence.
2. An engineering approach to software development and/or maintainence.
Some typical CASE tools are:
• Code generation tools.
• Data modeling tools.
• Refactoring tools.
• QVT or Model transformation Tools.
• Configuration management tools including revision control.
5.1.2
Classification of CASE Tools
A common classification of CASE Tools is on the basis of the stage of the
activities they support in the information systems life cycle. They can be
classified as Upper or Lower CASE tools.
Upper Case Tools support strategic, planning and construction of conceptual level product and ignore the design aspect. They support traditional diagrammatic languages such as ER Diagrams, DFD, Structure
charts etc.
18 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Lower Case Tools concentrate on the back end activities of the software life
cycle and hence support activities like physical design, debugging, construction, testing, integration of software components, maintainence,
reengineering and reverse engineering activties.
5.2
Lower CASE Tools
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
19 of 171
Chapter 6
Platforms: Hosts and Targets
This chapter provides general concepts about host and target platforms in the
development process.
6.1
Host Platforms
6.2
Target Platforms
20 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Part II
B ASIC P ROCESSES
Chapter 7
Modeling
7.1
On Modeling
Modeling is one of the central topics at ASLab. As stated in ?? ASys doc we
want to build systems from models of them, and we want to make them autonomous by the systems exploiting models of themselves, ideally the same
models used to construct them.
7.2
UML
UML is officially defined at the Object Management Group (OMG) by the
UML metamodel, a Meta-Object Facility metamodel (MOF). Like other MOFbased specifications, UML has allowed software developers to concentrate
more on design and architecture. UML models may be automatically transformed to other representations (e. g. Java) by means of QVT-like transformation languages, supported by the OMG. UML is extensible, offering the
following mechanisms for customization: profiles and stereotype. The semantics of extension by profiles have been improved with the UML 2.0 major
revision.
7.2.1
References
Links
www.omg.org
Bibliography available at ASLab
The Unified Modeling Language User Guide 2nd Edition, Booch, Rumbaugh
and Jacobson. Addison Wesley 2005.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
23 of 171
7.3
SysML
Links
www.omgsysml.org
Bibliography available at ASLab
7.4
ASLab Modeling Guideline
7.4.1
Modeling Tools
We are using principally modeling tools based on IBM RSD, but for different reasons we also use other tools such as Matlab, SystemML, BRAHMS,
Webots, etc. Briefly, we use:
• UML to model software specifically. We use RSD 7.0.5.1
• SysML to model more genral systems which include also physical parts.
We use Embedded Plus SysML Toolkit for this.
This section is under construction
24 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 8
Programming
The two first sections of this chapter describe the programming practices at
ASLab. The last section, in spanish, is a brief tutorial on programming in
C/C++ in a Linux environment
8.1
Coding
8.1.1
Coding Layout and Style
The techniques presented in this section doesn’t affect execution speed, memory usage or other aspects of a program that are visible from outside the program. They affect how easy it is to understand he code, review it, and revise
it months after you write it. They also affect how easy it is for others to read,
understand, and modify it. So it will be worth while for you and you partners
at ASLab if you spend a few minutes reading this.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
25 of 171
!!
The Fundamental Theorem of Formatting
Good visual layout shows the logical structure of a
program and improves readability (and usually looks
pretty):
• The first priority of visual layout is to illuminate
the logical organization of the code.
• Looking good is secondary to the previous priority.
• Structuring code its important for its own sake.
The specific convention is less important than
the fact of following it consistently.
• Do not get confuse the purpose of layout: it is
not about following some dogma, it is about accuracy, consistency, readability and maintainability.
8.1.2
Formatting Suggestions
Indenting
Indentation in C/C++ will only be useful from the layout perspective, and
will never cause compilation errors.
As a rule you should indent statements under the statement to which they
are logilally subordinate.
Blank Lines
A blank line will separate blocks of code performing diferent functionality.
The idea is to saparte the code into “paragraphs” representing logical blocks.
In the heading section (global declarations: include, define, typedef, const, etc)
each block of them must be separate by a blank line.
White Spaces
In C/C++ they do not affect the compilation, and we comment here how to
use them to improve code readability.
26 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
!!
Rules on white space between operators:
• With arithmetic and logical operators a white
space must separate the operator from it’s
operand.
• No white space will precede “,” or “;”
• No white space between operand and unitary
operator.
• With “<<” and “>>” operators more than a
white space may be used for clarity.
• No white spaces will be used with * and &
when they refer to pointers, and a white space
will be left when they are multiplication and
AND operations respectively.
Heading Section
Global declarations will be the second section of the file, only preceded by a
brief comment about the file, author purpose, etc.
The different blocks of the headings (include, define, typedef, const, etc) will be
separated by a blank line, starting with the includes and then const, typedef,
etc.
8.1.3
Comments
Refer to subsection 9.3.1
8.2
Programación en C/C++ con Linux
Esta sección trata sobre la programación en C/C++ en un entorno GNU/Linux.
En primer lugar se tratan los conceptos y herramientas básicos de programación en estos sistemas operativos, y en segundo lugar, se describe el entorno integrado de desarrollo KDevelop (versión 2.1).
8.2.1
Conceptos fundamentales
Para empezar a programar en GNU/Linux no hace falta nada más que un
simple editor de texto plano. Todas las distribuciones de este sistema operativo incluyen el programa gcc, acrónimo de GNU C Compiler, es decir, un
compilador para el lenguaje C. En realidad, gcc proporciona muchas más
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
27 of 171
funcionalidades que un simple compilador de C, pero no las describiremos
en detalle en este documento. Para saber más sobre gcc y el mundo de GNU
(GNU is Not Unix), se pueden visitar la página www.gnu.org y en particular
gcc.gnu.org.
Es posible crear un programa con sólo escribir el código en un editor de texto,
y pasarle el archivo al compilador gcc, o al g++. El compilador g++ viene a
ser una versión de gcc adecuada para compilar programas escritos en C++,
mientras que gcc se emplea para los programas escritos en C.
8.2.2
El ejemplo ”Hola mundo”
Como siempre se dice, a programar se aprende programando; por tanto vamos a ver cómo se harı́a el famoso programa ”Hola Mundo”.
Para empezar abrimos un editor de texto simple; los aficionados a la consola
usarán vi, y los que prefieran los entornos gráficos, gedit o kwrite, por
ejemplo. El programa ”Hola mundo” serı́a como sigue:
Escribiremos el programa y guardaremos el archivo dándole como extensión
una de las siguientes: .c, .cc ó .cpp. Por convenio suele usarse la primera
extensión para los archivos de código C puro, y las otras dos para aquellos
que contienen código de C++, aunque no es una regla obligatoria. El propio compilador reconoce el código y sabe cómo debe compilar el código, sin
necesidad de guiarse por la extensión del archivo. Yo tengo por costumbre
dar siempre la extensión .cpp, independientemente de lo que contenga el
archivo.
Una vez tengamos el archivo guardado, abrimos una consola y nos colocamos
en el directorio donde se encuentre dicho archivo. Ahora compilaremos el
archivo fuente para obtener el programa ejecutable. El gcc puede llegar a ser
muy complicado de manejar, dada la gran cantidad de parámetros que puede
recibir. Detallaremos los más utilizados (al menos por mı́) en el siguiente
apartado; de momento compilaremos nuestro programa con los parámetros
más básicos. La orden de compilación en la consola serı́a como sigue:
gcc -o holamundo holamundo.cpp
Con esta orden estamos arrancando el compilador, y le decimos que tome
como archivo fuente holamundo.cpp y que genere un archivo ejecutable
que se llame holamundo (parámetro -o). También podemos usar g++, aunque
conviene tener cuidado con ésto, ya que según el código de nuestro programa
y las funciones que se usen, gcc y g++ reaccionan de distinta manera. En
varias ocasiones me ha sucedido que gcc da un error con un archivo fuente,
y g++ lo procesa sin problemas.
Cuando el compilador termine, tendremos en el mismo directorio un ejecutable o binario. Podemos ejecutarlo (./holamundo) y ver cómo funciona.
En el siguiente apartado veremos qué otras opciones útiles se le pueden pasar
al gcc a la hora de compilar, aunque es muy recomendable aprender más de
este compilador consultando la página web de GNU, o bien las páginas MAN
28 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
del sistema operativo (man gcc).
8.2.3
Opciones del compilador gcc
A continuación se muestra una lista con las opciones de gcc que suelo utilizar más a menudo:
-O1, -O2, ...
-w
-c
-o [nombre]
-I[dir]
-L[dir]
-l[librerı́a]
-D[nombre]
-O9
Optimización de código (usar con cuidado)
Desactivar los warnings o mensajes de aviso.
Únicamente compilar los archivos, sin enlazarlos.
Nombre del ejecutable de salida (por defecto es a.out)
Directorios donde buscar archivos de cabecera .h
Directorios donde buscar librerı́as (.so, .a)
Orden de enlazar con una librerı́a dada.
Declaración de un nombre para preprocesamiento.
Para comprender mejor estas opciones pongamos un ejemplo: hemos escrito un programa cuyo código está repartido en tres archivos: main.cpp,
uno.cpp y dos.cpp. El programa necesita algunos archivos de cabecera
que se encuentran en el directorio /usr/share/include, y enlaza con la
librerı́a libCosa.so que se encuentra en el directorio /usr/share/lib.
Queremos hacer una optimización de código moderada, y que no nos moleste con mensajes de aviso durante la compilación. Ası́ mismo queremos
que el programa ejecutable se llame cosa.
Nota: Hay algunos convenios en Linux que conviene conocer: el nombre de
todas las librerı́as empieza por lib, pero cuando se quiere enlazar con
ellas se quita este prefijo y la extensión (.so ó .a) y se deja el resto. Las
liberı́as suelen encontrarse en directorios llamados lib, y los archivos
de cabecera en directorios include.
Dicho esto, la orden de compilación, asumiendo que los archivos .cpp se encuentran en el directorio actual, serı́a la siguiente:
gcc -O2 -W -I/usr/share/include -L/usr/share/lib -lCosa -o
cosa main.cpp uno.cpp dos.cpp
También podrı́amos separar el proceso de compilación del proceso de enlazado utilizando la opción -c, y hacer ésto mismo en cuatro pasos:
gcc -O2 -w -I/usr/share/include -c main.cpp
gcc -O2 -w -I/usr/share/include -c uno.cpp
gcc -O2 -w -I/usr/share/include -c dos.cpp
gcc -w -L/usr/share/lib -lCosa -o cosa main.o uno.o dos.o
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
29 of 171
Notar que cuando ordenamos a gcc que únicamente compile, su salida no
es un ejecutable sino un archivo objeto, con el mismo nombre que el archivo
fuente pero extensión .o. Además, en las órdenes de compilación no es necesario incluir la información sobre las librerı́as (-L y -l) ya que éstas se usan
sólamente a la hora de enlazar.
La última lı́nea ordena a gcc que enlace los archivos objeto (.o) y las librerı́as
necesarias (libCosa.so). En esta orden ya no es necesario el parámetro -O2
ya que se aplica a la compilación, no al enlazado. Además se indica el nombre
del ejecutable, ya que el enlazado tiene como resultado dicho archivo binario.
8.2.4
Make y los Makefiles
Después de compilar por enésima vez un programa y tener que escribir la
larga lı́nea de parámetros del gcc, cualquiera se preguntará si no hay una
forma mejor y más cómoda de hacer ésto. Dicha forma existe, y se llama
make.
Make es una herramienta muy utilizada en el mundo de GNU/Linux, que
se encarga de controlar la generación de los ejecutables de un programa, ası́
como de otros archivos no binarios relacionados. En realidad, la potencia de
make es enorme y puede utilizarse para una infinidad de tareas no directamente relacionadas con la generación de un archivo binario.
Usando make evitamos tener que escribir un sinnmero de rdenes y parmetros, cada vez que tenemos que compilar un programa: para ello únicamente
es necesario escribir ”make” en la consola, y si acaso, algún parámetro a continuación.
Make funciona a partir de un conjunto de reglas e indicaciones que el usuario
escribe en un archivo llamado Makefile. Dichas reglas indican al programa
la forma en que debe tratar los archivos fuente, y cómo y dónde debe generar
el archivo ejecutable. Los Makefiles pueden ser muy simples o increı́blemente
complejos. En mi opinión, antes de aprender a escribir makefiles complejos
conviene contentarse con unos conceptos básicos, y aprender antes a programar corréctamente en Linux. No tiene sentido escribir el llamado ”Makefile
universal” (utopı́a del mundillo de la programación GNU/Linux, un Makefile
que sirva para cualquier tipo de programa que deseemos crear), si no sabemos escribir un programa para aplicar dicho Makefile.
Sin embargo, llegado un momento es conveniente aprender algo más acerca
de estos archivos y la sintaxis que utilizan. Este documento no se centra en
la creación de makefiles, sino que muestra algunas de las reglas más básicas.
Para más detalles recomiendo algunas páginas:
• www.gnu.org/software/make/
• www.delorie.com/gnu/docs/make/
• www.edc.ncl.ac.uk/pages/comp/tutorial/make/
30 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
• www.eng.hawaii.edu/Tutor/Make/
Por el momento comentaremos los conceptos básicos de estos archivos, y
mostraremos un ejemplo muy sencillo aplicado a nuestro programa ”Hola
Mundo”. Este archivo contendrá los mismos parámetros que le pasábamos ”a
mano” al gcc, pero nos permitirá ahorrarnos escribirlos una y otra vez cada
vez que queramos recompilar nuestro programa. Después describiremos los
Makefiles con mayor detalle y mostraremos un ejemplo más complejo y
útil.
Un Makefile básico Los Makefiles son básicamente un conjunto de guı́as y
dependencias entre los archivos, que indican a make qué archivos debe utilizar
para contruir qué otro, y se escriben de la siguiente forma:
objetivo :
prerrequisito1 ...
prerrequisitoN
regla1
...
reglaN
Esta regla indicarı́a que para construir el objetivo (un archivo por ejemplo)
objetivo, es necesario que se cumplan los llamados prerrequisitos (a la
derecha de los dos puntos), que pueden ser archivos necesarios para construir el archivo objetivo. Dicho archivo se construye aplicando las reglas
indicadas debajo (puede haber una única orden o varias). Es importante indicar que las reglas deben ser precedidas por una tabulación, de lo contrario
make no entenderá la regla.
Sin entrar en demasiado detalle, diremos que make interpreta los Makefiles
de la siguiente manera: comienza a leer el archivo hasta que encuentra la primera
regla. Comprueba si ya dispone de los prerrequisitos de los que depende el
objetivo de la regla, y en caso de que le falte alguno, sigue leyendo las reglas que aparezcan a continuación, intentando encontrar una que le indique
cómo obtener el archivo o archivos que le faltan. Esto se hace de forma recursiva hasta que make ya sabe cómo obtener todos los archivos necesarios
para construir el objetivo. En ese momento aplica las operaciones que se le
han indicado en cada caso, y va realizando todas las operaciones necesarias
para obtener el archivo final.
Es importante resaltar que make ejecuta siempre la primera regla que encuentra, y no ejecuta ninguna otra regla más a menos que la/s necesite para obtener
algún elemento que ha encontrado en la primera.
Es muy común encontrar reglas sin dependencias, es decir, reglas que no
tienen nada a la derecha de los dos puntos (”:”). Estas reglas reciben el nombre de reglas phonic:
comando :
regla1
...
reglaN
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
31 of 171
Estas reglas no se utilizan para especificar las dependencias entre archivos,
sino para separar conjuntos de operaciones dentro del Makefile. No explicaremos el uso de éstas reglas hasta más adelante.
Sabiendo ésto, podemos presentar un primer ejemplo de Makefile, aplicado al programa ”Hola Mundo”. Recordemos que tenı́amos un ejecutable
cosa, que se construı́a (es decir, depende de) a partir de tres archivos fuente:
main.cpp, uno.cpp y dos.cpp. También tenı́amos algunos parámetros
que pasar a gcc.
Un Makefile muy simple para compilar nuestro programa serı́a el siguiente:
cosa:
main.o uno.o dos.o
gcc -w -L/usr/share/lib -lCosa -o cosa main.o uno.o dos.o
main.o:
main.cpp
gcc -O2 -w -I/usr/share/include -c main.cpp
uno.o:
uno.cpp
gcc -O2 -w -I/usr/share/include -c uno.cpp
dos.o:
dos.cpp
gcc -O2 -w -I/usr/share/include -c dos.cpp
En este Makefile existen cuatro reglas: la primera, o regla principal, indica
cómo obtener el ejecutable cosa a partir de los tres archivos objeto. Las tres
siguientes reglas indican cómo obtener dichos archivos objeto a partir de los
archivos de código fuente. Como decı́amos, las relgas del Makefile indican
las dependencias entre los diferentes archivos. Al leer el Makefile, realmente make sólo lee la primera regla, pero se da cuenta de que no dispone de
los archivos objeto (.o). Por ello busca otra regla entre las siguientes, que le
indique cómo obtener cada uno de esos archivos. Las tres reglas siguientes le
explican precı́samente ésto: como obtener (qué orden de procesamiento ejecutar) los archivos .o para cada uno de los archivos .cpp de los que make si
dispone.
Si uno se fija, se puede ver que el proceso que sigue make es precı́samente el
mismo que seguı́amos nosotros al hacer la compilación ”a mano”, separándola
en cuatro pasos.
En los siguientes apartados veremos con más detalle cómo son los Makefiles,
y mejoraremos el ejemplo anterior para hacerlo más flexible.
Makefiles complejos El Makefile del apartado anterior, aunque funcional,
es póco útil, ya que en el momento en que tengamos que cambiar un nombre a un archivo, o aÒadamos otro a nuestro programa, etc., nos veremos
obligados a editar muchas lı́neas del Makefile.
Por aÒadidura, en los casos en los que nuestro programa fuera bastante más
complejo, con muchos archivos y librerı́as repartidos en muchos directorios,
escribir un Makefile en esa situación serı́a ”un trabajo de chinos” y no apor-
32 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
tarı́a nada.
Para esos casos, conviene escribir los Makefiles de una forma algo diferente, aunque más compleja, utilizando variables, variables automáticas y funciones, dispuestas en una estructura determinada.
Estructura general Los Makefiles no tienen una estructura rı́gida. Sin embargo, es útil (y más claro) emplear siempre la misma forma de escribirlos.
La estructura que yo utilizo tiene siete partes diferenciadas:
• Declaración de variables principales
• Declaración de nombres de herramientas
• Declaración y asignación de flags
• Declaración de archivos fuente y objeto
• Declaración de la regla principal
• Declaración de reglas secundarias
• Declaración de otras operaciones
Los nombres y datos correspondientes a las cuatro primeras partes se almacenan utilizando variables, que se describen más adelante. Las tres últimas
partes se escriben en forma de reglas.
En la primera sección, incluyo las configuraciones más importantes para mi
programa, a saber: nombre y destino (path) del archivo ejecutable y directorios especiales usados para la compilación del programa en cuestión.
En la sección de nombres de herramientas, indico a make cuáles son los programas que debe utilizar para compilar o realizar otras operaciones: gcc,
g++, ar, etc. En estas dos primeras secciones se utilizan las variables de herramientas y una de las variables de archivos, que describiremos más adelante.
En la siguiente sección almaceno los parámetros de gcc de los que hablábamos
antes, comúnmente llamados ”flags”, en otras variables llamadas variables de
flags. En los Makefiles más complejos, pueden incluirse sentencias condicionales (tipo ”if”), para incluir o no algunos flags, según nuestras necesidades, pero ésto se sale del alcance de este documento.
A continuación se almacenan los nombres de los archivos fuente que deben
compilarse, y los nombres de los archivos objeto, en unas de las llamadas
variables de archivos.
Después se escribe la regla principal, de la que dependen todas las demás, y
que le dice a make cómo debe empezar a compilar. En la siguiente sección
se le proporciona el conjunto de subreglas que necesita para realizar la tarea
completa, escritas de la forma que ya hemos visto.
En la última sección se suelen incluir algunas operaciones útiles, como la
limpieza de directorios (borrado de los archivos intermedios que se crean
durante la compilación), la generación de documentación, etc.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
33 of 171
Variables Suele ser recomendable utilizar variables dentro de los Makefiles
para la configuración y creación de reglas, porque agilizan mucho el mantenimiento de los Makefiles. En la gran mayorı́a de los casos las variables
contienen nombres o listas de nombres separados por espacios. Por convenio, las variables se escriben en mayúsculas, aunque el programa Make es
”case insensitive”, es decir, no distingue entre mayúsculas y minúsculas.
Para recuperar el contenido de una variable se encierra su nombre entre
paréntesis, precedidos por un signo de dólar: por ejemplo, $(COSA) devuelve el contenido de la variable COSA.
Para rellenar una variable se escribe su nombre, seguido de un signo ”igual”
y su contenido o una función que se evalúa en su contenido. Un ejemplo de
variable que almacena una lista de nombres serı́a el siguiente:
COSA = hola.cpp adios.cpp chao.cpp
Si lo que se desea es aÒadir contenidos a la variable y no borrar lo que ya
contenı́a, en vez de un signo igual se escribe:
COSA := $(COSA) otro.cpp yotro.cpp
Con lo que la variable cosa contendrı́a ahora cinco nombres (hola.cpp,
adios.cpp, chao.cpp, otro.cpp y yotro.cpp).
Dentro de un Makefile yo uso, digamos, tres grupos de variables para almacenar distinta información:
de Herramientas: variables que almacenan el nombre de las herramientas
que utilizo.
de Flags: contienen los parámetros de los que hablábamos antes. Por claridad los separo en diferentes grupos, como veremos.
de Archivos: almacenan los nombres de los archivos fuente, los archivos objeto, el nombre del ejecutable, y otros.
A continuación muestro una lista de las variables más comúnmente utilizadas
en los Makefiles:
Variables de herramientas:
MAKE
CC
CPP
LD
Contiene el nombre de la herramienta de make (normalmente make, o gmake)
Contiene el nombre del compilador de C (normalmente gcc)
Contiene el nombre del compilador de C++ (normalmente g++)
Contiene el nombre del enlazador (normalmente g++)
Variables de archivos:
TARGET
SOURCES
OBJS
34 of 171
Contiene el path y el nombre del archivo ejecutable.
Contiene los archivos fuente.
Contiene los archivos objeto.
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Variables de flags:
CFLAGS
CPPFLAGS
LDFLAGS
LIBS
Contiene los flags pasados al compilador de C
Contiene los flags pasados al compilador de C++
Contiene los flags para el enlazador.
Contiene los nombres de las liberı́as con las que hay que enlazar.
En la inmensa mayorı́a de los casos, la variable CFLAGS es idéntica a CPPFLAGS.
Archivos Para especificar los archivos fuente y objeto de forma rápida y
cómoda, se emplean dos funciones especiales. La primera es la función wildcard.
Dicha función se evalúa en una lista de archivos que cumplan una determinada condición, por ejemplo, que tengan la extensión .cpp. Las funciones
dentro de los Makefiles se encierran entre paréntesis, precedidas por un
signo de dólar. Un ejemplo de uso de esta función en un Makefile serı́a el
siguiente:
ARCHIVOS = $(wildcard *.cpp)
Suponiendo que en el directorio donde se encuentra el Makefile hubiera
los siguientes archivos con extensión .cpp: uno.cpp, dos.cpp, tres.cpp,
la lı́nea anterior serı́a equivalente a escribir:
ARCHIVOS = uno.cpp dos.cpp tres.cpp
La ventaja es obvia: podemos rellenar una variable con una lista de archivos,
sin necesidad de tenerlos que escribir a mano. La segunda función es la
función patsubst, que realiza una sustitución de texto dentro de una lista
de nombres dada. Un uso muy común es utilizarla para obtener la lista de
nombres de archivo objeto, a partir de la lista de archivos fuente obtenida con
wildcard, como se muestra a continuación:
OBJETOS = $(patsubst %.o, %.cpp, $(wildcard *.cpp))
La lı́nea anterior se evaluarı́a de la siguiente forma: primero la función wildcard
se transforma en una lista de archivos .cpp. Después, la función patsubst
transforma esta lista intercambiando cada ”.cpp” por un ”.o”, como se especifica en sus argumentos. Los signos de porcentaje son comodines, es decir,
lo que se busca es sustituir ”cualquier cosa acabada en .cpp” por ”esa misma
cosa acabada en .o”. Ası́, la lı́nea anterior serı́a equivalente a la siguiente:
OBJETOS = uno.o dos.o tres.o
Para aprender más sobre las funciones de make, los sı́mbolos de comodı́n, etc.
es recomendable leer los tutoriales mencionados al principio del documento.
Reglas con variables En un Makefile más complejo las dependencias entre
archivos se incluyen de forma automática; es decir, no se escriben todos los
nombres de los archivos a mano. La regla principal del Makefile seguirá
siendo la misma, es decir, indicará que el archivo ejecutable depende de todos
los archivos objeto. Pero en vez de escribir explı́citamente estos archivos,
utilizamos las funciones especiales anteriores para rellenar la variable OBJS,
y escribiremos:
TARGET = cosa
OBJS = $(patsubst %.o, %.cpp, $(wildcard *.cpp))
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
35 of 171
# Regla principal:
$(TARGET) : $(OBJS)
Donde la variable TARGET contiene el nombre del archivo ejecutable, como
dijimos antes. La última lı́nea (la regla principal) se traduce a exáctamente la
primera lı́nea que escribimos en el primer Makefile.
Pero además de la regla principal, es necesario incluir una regla de dependencia para cada uno de los archivos objeto que se van a crear, como hicimos
en el primer Makefile. En vez de escribir estas reglas a mano, emplearemos una de las funcionalidades del programa gcc: cuando se le pasa como
parámetro el valor -M y como entrada un archivo .cpp, no lo compila sino
que genera una lista de dependencias de dicho archivo.
Esta lista de dependencias es precisamente una regla lista para incluir en un
Makefile, e indica que el archivo objeto correspondiente .o, depende del
archivo fuente .cpp que se pasó al gcc, y además incluye todos los archivos
de cabecera utilizados por dicho archivo fuente.
Entonces, utilizando una tuberı́a o ”pipe” (sı́mbolo >) para almacenar las
listas de dependencias generadas por gcc en un archivo, podemos aÒadir
automáticamente todas las reglas necesarias en el Makefile si incluimos el
archivo mencionado dentro del Makefile.
Para incluir un archivo dentro de un Makefile se emplea la directiva include,
seguida del nombre del archivo. Generalmente el archivo generado con gcc
-M suele llamarse ”.depend”.
El archivo de dependencias se generarı́a por tanto de la siguiente forma:
gcc -M -I/usr/share/include main.cpp uno.cpp dos.cpp > .depend
O, si empleamos las variables para almacenar los nombres de las herramientas y los flags,
CC = gcc
MISCOSAS INCDIR = /usr/share/include
CFLAGS = -I$(MISCOSAS INCDIR)
SOURCES = $(wildcard *.cpp)
$(CC) -M $(CFLAGS) $(SOURCES) > .depend
Donde hemos empleado la función wildcard para no tener que escribir a
mano todos los .cpp de nuestro programa, y hemos almacenado los flags
para gcc en la variable CFLAGS. Es muy frecuente hacer una división de
los flags más fina y separarlos en variables adicionales. En el ejemplo anterior, almacenamos el directorio /usr/share/include dentro de la variable
MISCOSAS INCDIR, y luego utilizamos esta variable para rellenar CFLAGS.
El archivo de dependencias debe incluirse después de la regla principal del
Makefile. Un detalle importante: como este archivo es generado desde
el Makefile, la primera vez que ejecutáramos make no existirı́a el archivo
36 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
”.depend” y make nos darı́a un error. Para evitar esto, encerraremos la regla
principal y la inclusión del archivo de dependencias en el interior de una sentencia condicional, que se ejecutará si y sólo si el archivo ”.depend” ya existe.
En caso contrario, no debe leerse regla principal y deberemos proporcionar
un ”camino secundario” al programa make, que resultará precisamente en la
generación del archivo de dependencias. Ası́, la siguiente vez que ejecutemos make el archivo de dependencias ya existirá y podremos compilar el
programa.
La regla principal y la sentencia de inclusión se escribirı́an ası́:
ifeq (.depend,$(wildcard .depend))
$(TARGET) : $(OBJS)
include .depend
endif
No hace falta centrarse mucho en la sintaxis de la sentencia condicional; basta
saber que es un ”truco” para que el código que hay entre ifeq y endif se
ejecutará sólamente si el archivo .depend existe.
Ahora ya tenemos las reglas que especifican las dependencias entre archivos,
pero no hemos dicho cómo deben procesarse éstos (no hemos puesto los comandos de gcc que escribı́amos en el primer Makefile). Para ello hay que
aÒadir otra regla más, que servirá para todo el conjunto de archivos objeto.
Cuando se usan variables para contener listas de archivos y no se especifican
reglas para cada archivo por separado, sino para un conjunto de archivos, hay
que usar sı́mbolos de comodı́n para escribir la regla. El sı́mbolo de comodı́n
más importante es el sı́mbolo de porcentaje (%) que es equivalente al asterisco en la consola. Por ejemplo, una regla que indique que todos los archivos
con una extensión determinada dependen de un archivo ”cosa.cpp”, se escribirı́a como sigue:
%.o :
cosa.cpp
Resulta más útil otra regla: aquella que indica que los archivos con extensión
.o dependen de sus homónimos con extensión .cpp. Se escribirı́a ası́:
%.o :
%.cpp
Lo cual nos permitirá indicar a make cómo debe compilar cada .cpp para
obtener su correspondiente .o. Sin embargo, al usar estos comodines, la orden de procesamiento no puede escribirse de cualquier forma, sino que hay
que usar otros sı́mbolos adicionales. ?stos sı́mbolos son los siguientes:
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
37 of 171
$@ - Indica el objetivo de la regla.
$< - Primer prerrequisito de la regla.
$ˆ - Conjunto de todos los prerrequisitos de la regla.
Con estos sı́mbolos, una regla que indicase cómo compilar cada archivo .cpp
para obtener su correspondiente .o se escribirı́a ası́:
%.o :
%.cpp
gcc -O2 -w -I/usr/share/include -o $@ -c $<
Que para cada uno de los archivos .cpp conocidos, se traducirı́a en la regla
correspondiente. Por ejemplo, para el archivo main.cpp:
main.o :
main.cpp
gcc -O2 -w -I/usr/share/include -o main.o -c main.cpp
La regla puede complicarse aún más, si utilizamos las variables que hemos
definido para las herramientas y los flags:
%.o :
%.cpp
$(CPP) $(CPPFLAGS) -o $@ -c $<
Tendrı́a el mismo resultado, con la ventaja de que una vez escrita ası́ la regla,
no tendremos que volver a tocarla aunque cambiemos un flag o el nombre de
un directorio que guarde los archivos de cabecera. En todo caso cambiarán
los contenidos de las variables, pero no la regla en sı́, lo cual es una ventaja.
Por último, sólo queda por aÒadir una regla: la que diga cómo obtener
el archivo ejecutable, a partir de los archivos objeto; es decir, la regla que
indique cómo enlazar (recordemos que hemos indicado que el archivo ejecutable depende de los archivos objeto, pero no hemos dicho cómo debe resolverse esta dependencia). Para ello emplearemos de nuevo los sı́mbolos especiales (también llamados variables automáticas). Dicha regla será la siguiente
(utilizamos g++ como enlazador):
% :
g++ -O2 -w -I/usr/share/include -L/usr/share/lib -o $@ $ˆ
-lCosa
Vemos que hemos usado el sı́mbolo especial que se traduce en la lista de
todos los prerrequisitos (en este caso, todos los archivos objeto). También
enlazamos con la librerı́a libCosa.so. Escribiendo la regla con variables,
% :
$(LD) $(CPPFLAGS) $(LDFLAGS) -o $@ $ˆ $(LIBS)
38 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
A primera vista las órdenes parecen muy crı́pticas, pero hay que intentar
imaginar en qué se convierte cada variable y cada sı́mbolo cuando son procesados. Una vez que se tiene práctica, la lectura de las reglas ası́ escritas es
prácticamente automática. En el siguiente apartado se ve de forma más clara
la colocación y escritura de todas estas reglas.
Un nuevo ejemplo Se muestra a continuación otro Makefile para el programa ”Hola mundo”, pero utilizando la estructura más compleja que hemos
descrito:
# Variables principales -------------------TARGET = cosa
MISCOSAS INCDIR = /usr/share/include
MISCOSAS LIBDIR = /usr/share/lib
# Herramientas ----------------------------CC = gcc
CPP = g++
LD = g++
MAKE = make
# Flags -----------------------------------CFLAGS = -O2 -w
CFLAGS := $(CFLAGS) -I$(MISCOSAS INCDIR)
CPPFLAGS = $(CFLAGS)
LDFLAGS = -L$(MISCOSAS LIBDIR)
LIBS = -lCosa
# Archivos --------------------------------SOURCES = $(wildcard *.cpp)
OBJS = $(patsubst %.o, %.cpp, $(wildcard *.cpp))
# Regla principal -------------------------ifeq (.depend,$(wildcard .depend))
$(TARGET) : $(OBJS)
include .depend
endif
# Reglas secundarias ----------------------%.o :
%.cpp
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
39 of 171
$(CPP) $(CPPFLAGS) -o $@ -c $<
% :
$(LD) $(CPPLAGS) $(LDFLAGS) -o $@ $ˆ $(LIBS)
dep :
$(CC) -M $(CFLAGS) $(SOURCES) > .depend
La regla ”dep” es el camino secundario del que antes hablábamos: si la sentencia condicional de la regla principal es falsa, es decir, si el archivo de dependencias no existe, el programa make saltará directamente a la primera
regla que tenga sentido para él, y esta es precisamente la regla ”dep.” En esta
regla se genera el archivo de dependencias.
De todos modos no es necesario ejecutar dos veces make para hacer esto. El
programa make permite pasarle como argumento una regla especı́fica contenida en el Makefile que queremos que se ejecute. Si le pasamos como
argumento el nombre de la regla ”dep”, conseguiremos que se genere el
archivo de dependencias, diréctamente.
Reglas adicionales Pueden incluirse otras reglas adicionales en forma similar a la regla ”dep”, las menciondadas reglas phonic. Hay dos reglas muy
conocidas: ”clean” y ”all”. La primera regla se encarga de limpiar todos los archivos intermedios generados durante la compilación (incluyendo
si queremos el archivo de dependencias), y la segunda realiza de golpe todos los pasos para generar el archivo ejecutable (en caso de que el proceso de
obtención constara de varios pasos). Estas reglas se escribirı́an ası́:
clean:
rm -f *.o
rm -f $(TARGET)
rm -f .depend
all:
$(MAKE) clean
$(MAKE)
Aquı́, la regla ”all” únicamente realiza en un paso lo que nosotros harı́amos
con dos llamadas a make: primero limpia los archivos intermedios (”make
clean”) y después recompila el programa (”make”).
Makefile completo Por último se muestra un Makefile con todo lo descrito hasta ahora:
# Variables principales -------------------TARGET = cosa
MISCOSAS INCDIR = /usr/share/include
40 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
MISCOSAS LIBDIR = /usr/share/lib
# Herramientas ----------------------------CC = gcc
CPP = g++
LD = g++
MAKE = make
# Flags -----------------------------------CFLAGS = -O2 -w
CFLAGS := $(CFLAGS) -I$(MISCOSAS INCDIR)
CPPFLAGS = $(CFLAGS)
LDFLAGS = -L$(MISCOSAS LIBDIR)
LIBS = -lCosa
# Archivos --------------------------------SOURCES = $(wildcard *.cpp)
OBJS = $(patsubst %.o, %.cpp, $(wildcard *.cpp))
# Regla principal -------------------------ifeq (.depend,$(wildcard .depend))
$(TARGET) : $(OBJS)
include .depend
endif
# Reglas secundarias ----------------------%.o :
%.cpp
$(CPP) $(CPPFLAGS) -o $@ -c $<
% :
$(LD) $(CPPLAGS) $(LDFLAGS) -o $@ $ˆ $(LIBS)
dep :
$(CC) -M $(CFLAGS) $(SOURCES) > .depend
# Reglas adicionales ----------------------clean:
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
41 of 171
rm -f *.o
rm -f $(TARGET)
rm -f .depend
all:
$(MAKE) clean
$(MAKE)
# ------------------------------------------
42 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 9
Documentation
9.1
Introduction
Documentation is not a nice, elegant practice, used to increase the volume of
the deliverables of a project. Documentation is a necessity:
• For reusability
• For maintainability
• For scalability
• To remember what you did yesterday!!
So this chapter provides the guidelines for documenting any development
your may be doing, with special emphasis in code documentation. There
would be some fixed rules about documenting, but most of the following
would be useful recommendations to be used when applicable that can help
not only other but yourself.
9.2
Documenting Hardware
9.3
Documenting Software
Documentation on a software project consist of information both inside the
source-code and in external documents.
9.3.1
Self-Documenting Code: Comments
In contrast to external documentation, internal documentation is found within
the source-code itself. it is the most detailed kind of documentation and the
most likely to remain correct as the code is modified.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
43 of 171
!!
Keep comments actualized when modifying the code
The main contributor to code-level documentation isn’t comments, but good
programming style (see 8.1)
Kinds of Comments
There are only two useful types of comments:
A summary of the code: comment distills a few lines of codes into one or
more sentences.
A description of the code’s intent: comment explains at the level of the problem the purpose of a section of the code.
The distinction between both is not always clear, and it is usually not important.
!!
Comments used to explain the code means that the
code is too complcated and/or confusing. So do not
explain it with long comments: improve and make
the code clear and then use summary or intent comments.
Key Points
• The question of whether to comment is a legitimate one. Done poorly,
commenting is a waste of time and sometimes harmful. Done well,
commenting is worthwhile.
• The source-code listing should contain most of the critical information
about the program. As long as the program is running, the listing is
the only document that’s garanteed not to be lost or discarded, and it’s
useful to have important information bundled with the code.
• Good comments are written at the level of intent. They explain the why
more than the how.
44 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
!!
ASLab Commenting Rules:
1. Comment.
2. Comment.
3. Comment.
4. Comment in English, please. If Spanish is desired for understandability, do not put accentuation marks.
9.3.2
External Documentation
At ASLab we are compromised with the production of modular and reusable
software artifacts, so developers should produce two kinds of documentation
accompannying each artifact they produce: inner view documentation and
external view documentation:
External view documentation: must provide information to developers that
are going to use the artifact without modifying it – i.e. those building
artifacts that make use of functionality provided by it, or that provide
funcionality to it –. This external view consist of precisely documenting
the IDL (in the case of a CORBA component) or interface of the artifact.
Inner view documentation: general information about the source code of
the artifact: programming language and version. In addition it must
provide two kinds of information:
Information for future developers responsible for the artifact, consisting of code comments. Information for developers building and
deploying the art on a target:
• OS: name and version (i.e. Windows XP SP2, Debian Linux XXX.XXX)
• APIs and Libraries needed (i.e. Aria XXX.XXX)
!!
9.4
Documenting your piece of software (a class, an
IDL,. . . ): Write a summary and intention comment on
the methods and explain what each attribute is. Then
generate the external documentation using Doxygen
(see 9.4).
Doxygen
Source code documentation generator tool.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
45 of 171
Doxygen is a documentation system for C++, C, Java, Objective-C, Python,
IDL (Corba and Microsoft flavors) and to some extent PHP, C#, and D.
It can help you in three ways:
1. It can generate an on-line documentation browser (in HTML) and/or
an off-line reference manual (in LATEX) from a set of documented source
files. There is also support for generating output in RTF (MS-Word),
PostScript, hyperlinked PDF, compressed HTML, and Unix man pages.
The documentation is extracted directly from the sources, which makes
it much easier to keep the documentation consistent with the source
code.
2. You can configure doxygen to extract the code structure from undocumented source files. This is very useful to quickly find your way in
large source distributions. You can also visualize the relations between
the various elements by means of include dependency graphs, inheritance diagrams, and collaboration diagrams, which are all generated
automatically.
3. You can even ‘abuse’ doxygen for creating normal documentation (as I
did for this manual).
Doxygen is developed under Linux and Mac OS X, but is set-up to be highly
portable. As a result, it runs on most other Unix flavors as well. Furthermore,
executables for Windows are available.
9.4.1
Information in the index page
To get information on the index page in HTML you should use the \mainpage
command inside a comment block like this:
/*! \mainpage My Personal Index Page
*
* \section intro_sec Introduction
*
* This is the introduction.
*
* \section install_sec Installation
*
* \subsection step1 Step 1: Opening the box
*
* etc...
*/
9.4.2
Special documentation blocks
A special documentation block is a C or C++ style comment block with some
additional markings, so doxygen knows it is a piece of documentation that
46 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
needs to end up in the generated documentation. For Python code there is a
different comment convention, which can be found in section Special documentation blocks in Python
For each code item there are two types of descriptions, which together form
the documentation: a brief description and detailed description, both are optional. Having more than one brief or detailed description however, is not
allowed.
As the name suggest, a brief description is a short one-liner, whereas the detailed description provides longer, more detailed documentation.
There are several ways to mark a comment block as a detailed description:
1. You can use the JavaDoc style, which consist of a C-style comment block
starting with two *’s, like this:
/**
* ... text ...
*/
2. or you can use the Qt style and add an exclamation mark (!) after the
opening of a C-style comment block, as shown in this example:
/*!
* ... text ...
*/
In both cases the intermediate *’s are optional, so
/*!
... text ...
*/
is also valid.
3. A third alternative is to use a block of at least two C++ comment lines,
where each line starts with an additional slash or an exclamation mark. Here
are examples of the two cases:
///
/// ... text ...
///
or
//!
//!... text ...
//!
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
47 of 171
4.
Some people like to make their comment blocks more visible in the documentation. For this purpose you can use the following:
/////////////////////////////////////////////////
/// ... text ...
/////////////////////////////////////////////////
For the brief description there are also several posibilities:
1. One could use the \ brief command with one of the above comment blocks.
This command ends at the end of a paragraph, so the detailed description
follows after an empty line.
Here is an example:
/*! \brief Brief description.
Brief description continued.
*
*
* Detailed description starts here.
*/
2. If JAVADOC AUTOBRIEF is set to YES in the configuration file, then using JavaDoc style comment blocks will automatically start a brief description
which ends at the first dot followed by a space or new line. Here is an example:
/** Brief description which ends at this dot. Details follow
* here.
*/
The option has the same effect for multi-line special C++ comments:
/// Brief description which ends at this dot. Details follow
/// here.
3. A third option is to use a special C++ style comment which does not span
more than one line. Here are two examples:
/// Brief description.
/** Detailed description. */
or
//! Brief descripion.
//! Detailed description
//! starts here.
48 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Note the blank line in the last example, which is required to separate the
brief description from the block containing the detailed description. The
JAVADOC AUTOBRIEF should also be set to NO for this case.
As you can see doxygen is quite flexible. The following however is not legal
//! Brief description, which is
//! really a detailed description since it spans multiple lines.
/*! Oops, another detailed description!
*/
because doxygen only allows one brief and one detailed description.
Furthermore, if there is one brief description before a declaration and one
before a definition of a code item, only the one before the declaration will be
used. If the same situation occurs for a detailed description, the one before
the definition is preferred and the one before the declaration will be ignored.
Qt style
Here is an example of a documented piece of C++ code using the Qt style:
//! A test class.
/*!
A more elaborate class description.
*/
class Test
{
public:
//! An enum.
/*! More detailed enum description.
enum TEnum {
TVal1, /*!< Enum value
TVal2, /*!< Enum value
TVal3 /*!< Enum value
}
//! Enum pointer.
/*! Details. */
*enumPtr,
//! Enum variable.
/*! Details. */
enumVar;
*/
TVal1. */
TVal2. */
TVal3. */
//! A constructor.
/*!
A more elaborate description of the constructor.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
49 of 171
*/
Test();
//! A destructor.
/*!
A more elaborate description of the destructor.
*/
˜Test();
//! A normal member taking two arguments and returning an intege
/*!
\param a an integer argument.
\param s a constant character pointer.
\return The test results
\sa Test(), ˜Test(), testMeToo() and publicVar()
/
*
int testMe(int a,const char *s);
//! A pure virtual member.
/*!
\sa testMe()
\param c1 the first argument.
\param c2 the second argument.
/
*
virtual void testMeToo(char c1,char c2) = 0;
//! A public variable.
/*!
Details.
/
*
int publicVar;
//! A function variable.
/*!
Details.
*/
int (*handler)(int a,int b);
};
The one-line comments contain a brief description, whereas the multi-line
comment blocks contain a more detailed description.
The brief descriptions are included in the member overview of a class, namespace or file and are printed using a small italic font (this description can be
hidden by setting BRIEF MEMBER DESC to NO in the config file). By default the brief descriptions become the first sentence of the detailed descriptions (but this can be changed by setting the REPEAT BRIEF tag to NO). Both
the brief and the detailed descriptions are optional for the Qt style.
50 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
JavaDoc style
By default a JavaDoc style documentation block behaves the same way as a
Qt style documentation block. This is not according the JavaDoc specification
however, where the first sentence of the documentation block is automatically treated as a brief description. To enable this behaviour you should set
JAVADOC AUTOBRIEF to YES in the configuration file. If you enable this
option and want to put a dot in the middle of a sentence without ending it,
you should put a backslash and a space after it. Here is an example:
/** Brief description (e.g.\ using only a few words). Details fol
Here is the same piece of code as shown above, this time documented using
the JavaDoc style and JAVADOC AUTOBRIEF set to YES:
/**
* A test class. A more elaborate class description.
*/
class Test
{
public:
/**
* An enum.
* More detailed enum description.
*/
enum TEnum {
TVal1,
TVal2,
TVal3
}
enumPtr,
*
enumVar;
/**< enum value TVal1. */
/**< enum value TVal2. */
/**< enum value TVal3. */
/**< enum pointer. Details. */
/**< enum variable. Details. */
/**
* A constructor.
* A more elaborate description of the constructor.
*/
Test();
/**
* A destructor.
* A more elaborate description of the destructor.
*/
˜Test();
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
51 of 171
/**
* a normal member taking two arguments and returning an integ
* @param a an integer argument.
* @param s a constant character pointer.
* @see Test()
* @see ˜Test()
* @see testMeToo()
* @see publicVar()
* @return The test results
*/
int testMe(int a,const char *s);
/**
* A pure virtual member.
* @see testMe()
* @param c1 the first argument.
* @param c2 the second argument.
*/
virtual void testMeToo(char c1,char c2) = 0;
/**
* a public variable.
* Details.
*/
int publicVar;
/**
* a function variable.
* Details.
*/
int (*handler)(int a,int b);
};
Similarly, if one wishes the first sentence of a Qt style documentation block to
automatically be treated as a brief description, one may set QT AUTOBRIEF
to YES in the configuration file.
Unlike most other documentation systems, doxygen also allows you to put
the documentation of members (including global functions) in front of the
definition. This way the documentation can be placed in the source file instead of the header file. This keeps the header file compact, and allows the
implementer of the members more direct access to the documentation. As a
compromise the brief description could be placed before the declaration and
the detailed description before the member definition.
52 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
9.4.3
Putting documentation after members
If you want to document the members of a file, struct, union, class, or enum,
and you want to put the documentation for these members inside the compound, it is sometimes desired to place the documentation block after the
member instead of before. For this purpose you have to put an additional ¡
marker in the comment block. Note that this also works for the parameters
of a function.
Here are some examples:
int var; /*!< Detailed description after the member */
This block can be used to put a Qt style detailed documentation block after a
member. Other ways to do the same are:
int var; /**< Detailed description after the member */
or
int var; //!< Detailed description after the member
//!<
or
int var; ///< Detailed description after the member
///<
Most often one only wants to put a brief description after a member. This is
done as follows:
int var; //!< Brief description after the member
or
int var; ///< Brief description after the member
Note that these blocks have the same structure and meaning as the special
comment blocks in the previous section only the ¡ indicates that the member
is located in front of the block instead of after the block.
Here is an example of the use of these comment blocks:
/*! A test class */
class Test
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
53 of 171
{
public:
/** An enum type.
* The documentation
*/
enum EnumType
{
int EVal1,
/**<
int EVal2
/**<
};
void member();
//!<
protected:
int value;
block cannot be put after the enum!
enum value 1 */
enum value 2 */
a member function.
/*!< an integer value */
};
Warning: These blocks can only be used to document members and parameters. They cannot be used to document files, classes, unions, structs, groups,
namespaces and enums themselves. Furthermore, the structural commands
mentioned in the next section (like \class) are ignored inside these comment
blocks.
9.4.4
Documentation at other places
So far we have assumed that the documentation blocks are always located
in front of the declaration or definition of a file, class or namespace or in
front or after one of its members. Although this is often comfortable, there
may sometimes be reasons to put the documentation somewhere else. For
documenting a file this is even required since there is no such thing as ”in
front of a file”.
Doxygen allows you to put your documentation blocks practically anywhere
(the exception is inside the body of a function or inside a normal C style
comment block).
The price you pay for not putting the documentation block directly before (or
after) an item is the need to put a structural command inside the documentation block, which leads to some duplication of information. So in practice
you should avoid the use of structural commands unless other requirements
force you to do so.
Structural commands (like all other commands) start with a backslash (\), or
an at-sign (@) if you prefer JavaDoc style, followed by a command name and
one or more parameters. For instance, if you want to document the class Test
in the example above, you could have also put the following documentation
block somewhere in the input that is read by doxygen:
/*! \class Test
\brief A test class.
54 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
A more detailed class description.
*/
Here the special command \class is used to indicate that the comment block
contains documentation for the class Test. Other structural commands are:
* \struct to document a C-struct. * \union to document a union. * \enum
to document an enumeration type. * \fn to document a function. * \var to
document a variable or typedef or enum value. * \def to document a #define. * \typedef to document a type definition. * \file to document a file. *
\namespace to document a namespace. * \package to document a Java package. * \interface to document an IDL interface.
See section Special Commands for detailed information about these and many
other commands.
To document a member of a C++ class, you must also document the class
itself. The same holds for namespaces. To document a global C function,
typedef, enum or preprocessor definition you must first document the file
that contains it (usually this will be a header file, because that file contains
the information that is exported to other source files).
Let’s repeat that, because it is often overlooked: to document global objects
(functions, typedefs, enum, macros, etc), you must document the file in which
they are defined. In other words, there must at least be a
/*! \file */
or a
/** @file */
line in this file.
Here is an example of a C header named structcmd.h that is documented
using structural commands:
/*! \file structcmd.h
\brief A Documented file.
Details.
*/
/*! \def MAX(a,b)
\brief A macro that returns the maximum of \a a and \a b.
Details.
*/
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
55 of 171
/*! \var typedef unsigned int UINT32
\brief A type definition for a .
Details.
*/
/*! \var int errno
\brief Contains the last error code.
\warning Not thread safe!
*/
/*! \fn int open(const char *pathname,int flags)
\brief Opens a file descriptor.
\param pathname The name of the descriptor.
\param flags Opening flags.
*/
/*! \fn int close(int fd)
\brief Closes the file descriptor \a fd.
\param fd The descriptor to close.
*/
/*! \fn size_t write(int fd,const char *buf, size_t count)
\brief Writes \a count bytes from \a buf to the filedescriptor \
\param fd The descriptor to write to.
\param buf The data buffer to write.
\param count The number of bytes to write.
/
*
/*! \fn int read(int fd,char *buf,size_t count)
\brief Read bytes from a file descriptor.
\param fd The descriptor to read from.
\param buf The buffer to read into.
\param count The number of bytes to read.
/
*
#define MAX(a,b) (((a)>(b))?(a):(b))
typedef unsigned int UINT32;
int errno;
int open(const char *,int);
int close(int);
size_t write(int,const char *, size_t);
int read(int,char *,size_t);
Because each comment block in the example above contains a structural command, all the comment blocks could be moved to another location or input
56 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
file (the source file for instance), without affecting the generated documentation. The disadvantage of this approach is that prototypes are duplicated,
so all changes have to be made twice! Because of this you should first consider if this is really needed, and avoid structural commands if possible. I
often receive examples that contain \fn command in comment blocks which
are place in front of a function. This is clearly a case where the \fn command
is redundant and will only lead to problems.
9.4.5
Special documentation blocks in Python
For Python there is a standard way of documenting the code using so called
documentation strings. Such strings are stored in doc and can be retrieved
at runtime. Doxygen will extract such comments and assume they have to be
represented in a preformatted way.
"""Documentation for this module.
More details.
"""
def func():
"""Documentation for a function.
More details.
"""
pass
class PyClass:
"""Documentation for a class.
More details.
"""
def __init__(self):
"""The constructor."""
self._memVar = 0;
def PyMethod(self):
"""Documentation for a method."""
pass
Note that in this case none of doxygen’s special commands are supported.
There is also another way to document Python code using comments that
start with “##”. These type of comment blocks are more in line with the way
documentation blocks work for the other languages supported by doxygen
and this also allows the use of special commands.
Here is the same example again but now using doxygen style comments:
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
57 of 171
## Documentation for this module.
#
# More details.
## Documentation for a function.
#
# More details.
def func():
pass
## Documentation for a class.
#
# More details.
class PyClass:
## The constructor.
def __init__(self):
self._memVar = 0;
## Documentation for a method.
# @param self The object pointer.
def PyMethod(self):
pass
## A class variable.
classVar = 0;
## @var _memVar
# a member variable
Since python looks more like Java than like C or C++, you should set OPTMIZE OUTPUT JAVA to YES in the config file.
58 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 10
Testing
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
59 of 171
Part III
T OOLSET
Chapter 11
RSD and Eclipse
This chapter presents the main tool at ASLab: Rational System Developer
(RSD), and all you need to know to rapidly get productive at our research
group.
11.1
Why this is the most important chapter of the manual
Currently, the central tool at ASLab is Rational System Developer (RSD
7.0.5.1), an eclipse based IBM tool. We wanted it use it for modeling, both
in UML and SysML, but we choose it between other alternatives because this
single tool allows us to: access CVS repository, develop software, build software and even write latex!! Leaving out the modeling, the rest of the features
of RSD are the same as those of a plain Eclipse framework, so the instructions
presented in the following section are the same for both.1
11.2
RSD
For information on RSD:
http://www.ibm.com/developerworks/rational/products/rsd/
11.3
Using CVS
See 12.5
1
if you, as most part of the group, work in Mac OS, you will have to run a Linux or Windows virtualization, since there is no Mac OS version of RSD, to do modelling. But if you just
want to get other resources from cvs, such as latex projects, you can do it with a plain Eclipse
on your Mac without virtualizing anything.
62 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
11.4
Using RSD as an UML modeling platform
Under Construction
11.5
Using RSD as a SysML modeling platform
To develop SysML model with RSD you need EmbeddedPlus SysML plugin You can download the latest version of the plug-in only for windows
accesing with ftp and your username and password ASLab server sagan
(138.100.76.251). Once logged you can find it at: /opt/software/RSD/
Once downloaded you only need to follow the attached instructions to install
the plug-in in your RSD.
11.6
Using Eclipse as a LaTeX environment
TeXlipse2 is a plugin that adds Latex support to the Eclipse IDE.
To install, just add http://texlipse.sourceforge.net to the list of update sites.
Figure 11.1: Screen capture of the TeXlipse plug-in.
To poperly use it it is necessary to configure TeXlipse for the LaTeX environment available in the computer. This is done in the Eclipse Preferences panel.
There, it is possible to configure external applications used by the TeXlipse
plug-in (LaTeX compilers, viewers, bibtexers, indexers, etc.).
2
http://texlipse.sourceforge.net/
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
63 of 171
Some special hacking may be necessary forthe Mac OS X as the previewers
may be external PDF view applications —for example Mac OS X Preview
or Acrobat— and the configuration panel just lets select one executable and
cannot navigate inside application packages.
A simple walkaround is to execute the viewer through a shell script using the
OS X ’open’ command:
#!/bin/bash
open -a Preview $1
64 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 12
CVS
Keywords: Release management, CVS
12.1
Tool domain
Revision control is a necessary practice in any serious code endeavor. This
document describes the setting, configuration and use policies of the ASLab
CVS repository.
CVS is the Concurrent Versions System, the dominant open-source networktransparent version control system. CVS is useful for everyone from individual developers to large, distributed teams and that is the reason for using it
as ASLab.
12.2
Introduction
12.2.1
Purpose
This report describes the use of the ASLab CVS system. The Concurrent
Versioning System is a repository-based, transactional system for software
release management.
CVS implements a version control system keeping track of all work and all
changes in a set of files, typically the implementation of a software project,
and allows several (potentially widely separated) developers to collaborate.
CVS has become popular in the open-source world due to its consolidated
functionality, simplicity of use and the fact that CVS is released under the
GNU General Public License.
Other alternatives do exist —even more modern ones like Subversion—, but
CVS is a well established technology and is incorporated in many integrated
environments (e.g. Eclipse).
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
65 of 171
12.2.2
Audience
This document is meant to be read by the ASLab people, not only developers
but everyboyd involved in the production os ASLab assets.
CVS is not only useful for group development coordination. It is also useful
for a single developer as a versioning control tool, backup system, etc.
12.2.3
Sources
This report is strongly based on CVS source material, including Jim Blandy
introduction.
12.2.4
A Bit of CVS Terminology
A single project (set of related files) managed by CVS is called a module. A
CVS server stores the modules it manages in its repository. Acquiring a copy
of a module is called checking out. The checked out files serve as a working
copy. One’s changes to the working copy will be reflected in the repository
by commit[ting] them. To update is to acquire the latest changes from the
repository in the working copy.
12.3
Introduction to CVS
12.3.1
What is CVS for?
CVS maintains a history of a source tree, in terms of a series of changes. It
stamps each change with the time it was made and the user name of the
person who made it. Usually, the person provides a bit of text describing
why they made the change as well. Given that information, CVS can help
developers answer questions like:
• Who made a given change?
• When did they make it?
• Why did they make it?
• What other changes did they make at the same time?
12.3.2
How to use CVS – First Sketch
Before discussing too many vague terms and concepts, let’s look over the
essential CVS commands.
Setting your repository
66 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
CVS records everyone’s changes to a given project in a directory tree called a
repository. Before you can use CVS, you need to set the CVSROOT environment variable to the repository’s path. Whoever is in charge of your project’s
configuration management will know what this is; perhaps they’ve made a
global definition for CVSROOT somewhere.
In any case, on our system, the CVS repository is located in the tierra server
directory ‘ /home/cvsroot ’. So, you would need to enter the command
export CVSROOT=/home/cvsroot
if your shell is Bash or some other Bourne shell variant.
If you forget to do this, CVS will complain when you try to use it:
$ cvs checkout httpc
cvs checkout: No CVSROOT specified!
option
Please use the ‘-d’
cvs [checkout aborted]: or set the CVSROOT environment
variable.
$
Unfortunately this definition only works if you are working in the server
where the repository resides, but most of the time you will be working in a
different host.
To use the ASLab CVS server remotely you must define the CVSROOT variable as follows (for example in .bashrc ):
export CVSROOT=:ext:username@tierra:/home/cvsroot
where username is your username in the ASLab NIS system.
Starting a project with CVS
Because renaming files and moving them between directories is somewhat
inconvenient, the first thing you do when you start a new project should be to
think through your file organization. It is not impossible to rename or move
files, but it does increase the potential for confusion and CVS does have some
quirks particularly in the area of renaming directories.
What to do next depends on the situation at hand.
Setting up the files
The first step is to create the files inside the repository. This can be done in a
couple of different ways.
Creating a directory tree from a number of files This method is useful with
old projects where files already exists.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
67 of 171
Creating Files From Other Version Control Systems Old projects where you
want to preserve history from another system.
Creating a directory tree from scratch
The most common case will be creating a directory tree from a number of
files. When you begin using CVS, you will probably already have several
projects that can be put under CVS control. In these cases the easiest way is to
use the import command. An example is probably the easiest way to explain
how to use it. If the files you want to install in CVS reside in ‘wdir’, and you
want them to appear in the repository as ‘$CVSROOT/yoyodyne/rdir’, you
can do this:
$ cd wdir $ cvs import -m "Imported sources" yoyodyne/rdir yoyo
start
Unless you supply a log message with the ‘-m’ flag, CVS starts an editor and
prompts for a message. The string ‘yoyo’ is a vendor tag, and ‘start’ is a
release tag. They may fill no purpose in this context, but since CVS requires
them they must be present.
You can now verify that it worked, and remove your original source directory.
$ cd .. $ cvs checkout yoyodyne/rdir $ diff -r wdir yoyodyne/rdir
$ rm -r wdir
Erasing the original sources is a good idea, to make sure that you do not
accidentally edit them in wdir, bypassing CVS. Of course, it would be wise
to make sure that you have a backup of the sources before you remove them.
The checkout command can either take a module name as argument (as it has
done in all previous examples) or a path name relative to $CVSROOT, as it
did in the example above.
It is a good idea to check that the permissions CVS sets on the directories
inside $CVSROOT are reasonable, and that they belong to the proper groups.
If some of the files you want to import are binary, you may want to use the
wrappers features to specify which files are binary and which are not.
Checking out a working directory
CVS doesn’t work on ordinary directory trees; you need to work within a
directory that CVS created for you. Just as you check out a book from a library
before taking it home to read it, you use the cvs checkout command to
get a directory tree from CVS before working on it. For example, suppose
you are working on a project named httpc , a trivial HTTP client:
$ cd
$ cvs checkout httpc
cvs checkout: Updating httpc
U httpc/.cvsignore
68 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
U httpc/Makefile
U httpc/httpc.c
U httpc/poll-server
$
The command cvs checkout httpc means, ”Check out the source tree
called httpc from the repository specified by the CVSROOT environment
variable.”
CVS puts the tree in a subdirectory named ‘httpc’:
$ cd httpc
$ ls -l
total 8
drwxr-xr-x
-rw-r--r--rw-r--r--rwxr-xr-x
2
1
1
1
jimb
jimb
jimb
jimb
512
89
4432
460
Oct
Oct
Oct
Oct
31
31
31
30
11:04
10:42
10:45
10:21
CVS
Makefile
httpc.c
poll-server
Most of these files are your working copies of the httpc sources. However,
the subdirectory called ‘CVS’ (at the top) is different. CVS uses it to record
extra information about each of the files in that directory, to help it determine
what changes you’ve made since you checked it out.
Making changes to files
Once CVS has created a working directory tree, you can edit, compile and
test the files it contains in the usual way – they’re just files.
For example, suppose we try compiling the package we just checked out:
$ make
gcc -g -Wall
-lnsl -lsocket
httpc.c
-o httpc
httpc.c: In function ‘tcp_connection’:
httpc.c:48: warning: passing arg 2 of ‘connect’ from
incompatible pointer type
It seems that ‘httpc.c’ hasn’t been ported to this operating system yet. We
need to cast one of the arguments to connect. To fix that, line 48 must change
from this:
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
69 of 171
if (connect (sock, &name, sizeof (name)) >= 0)
to this:
if (connect(sock, (struct sockaddr *) &name, sizeof(name))
>= 0)
Now it should compile:
$ make
gcc -g -Wall
-lnsl -lsocket
httpc.c
-o httpc
$ httpc GET http://www.cyclic.com
... HTML text for Cyclic Software’s home page follows ...
$
Merging your changes
Since each developer uses their own working directory, the changes you make
to your working directory aren’t automatically visible to the other developers
on your team. CVS doesn’t publish your changes until you’re ready. When
you’re done testing your changes, you must commit them to the repository to
make them available to the rest of the group. We’ll describe the cvs commit
command below.
However, what if another developer has changed the same files you have, or
the same lines? Whose changes should prevail? It’s generally impossible to
answer this question automatically; CVS certainly isn’t competent to make
that judgment.
Thus, before you can commit your changes, CVS requires your sources to be
in sync with any changes committed by the other team members. The cvs
update command takes care of this:
$ cvs update
cvs update: Updating .
U Makefile
RCS file: /u/src/master/httpc/httpc.c,v
retrieving revision 1.6
retrieving revision 1.7
70 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Merging differences between 1.6 and 1.7 into httpc.c
M httpc.c
$
Let’s look at this line-by-line:
U Makefile
A line of the form ‘U file’ means that file was simply Updated; someone else
had made a change to the file, and CVS copied the modified file into your
home directory.
RCS file: ...
retrieving revision 1.6
retrieving revision 1.7
Merging differences between 1.6 and 1.7 into httpc.c
These messages indicate that someone else has changed ‘httpc.c’; CVS merged
their changes with yours, and did not find any textual conflicts. The numbers ‘1.6’ and 1.7 are revision numbers, used to identify a specific point in a
file’s history. Note that CVS merges changes into your working copy only;
the repository and the other developers’ working directories are left undisturbed. It is up to you to test the merged text, and make sure it’s valid.
M httpc.c
A line of the form ‘M file’ means that file has been Modified by you, and
contains changes that are not yet visible to the other developers. These are
changes you need to commit. In this case, ‘httpc.c’ now contains both your
modifications and those of the other user.
Since CVS has merged someone else’s changes into your source, it’s best to
make sure things still work:
$ make
gcc -g -Wall -Wmissing-prototypes -lnsl -lsocket httpc.c
-o httpc
$ httpc GET http://www.cyclic.com
... HTML text for Cyclic Software’s home page follows ...
$
It seems to still work.
Committing your changes
Now that you have brought your sources up to date with the rest of the group
and tested them, you are ready to commit your changes to the repository and
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
71 of 171
make them visible to the rest of the group. The only file you’ve modified is
‘httpc.c’, but it’s always safe to run cvs update to get a list of the modified
files from CVS:
$ cvs update
cvs update: Updating .
M httpc.c
$
As expected, the only file CVS mentions is ‘httpc.c’; it says it contains changes
which you have not yet committed. You can commit them like so:
$ cvs commit httpc.c
At this point, CVS will start up your favorite editor and prompt you for a log
message describing the change. When you exit the editor, CVS will commit
your change:
Checking in httpc.c;
/u/src/master/httpc/httpc.c,v
<--
httpc.c
new revision: 1.8; previous revision: 1.7
$
Now that you have committed your changes, they are visible to the rest of
the group. When another developer runs cvs update, CVS will merge your
changes to ‘httpc.c’ into their working directory.
Examining changes
At this point, you might well be curious what changes the other developer
made to ‘httpc.c’. To look at the log entries for a given file, you can use the
cvs log command:
$ cvs log httpc.c
RCS file: /u/src/master/httpc/httpc.c,v
Working file: httpc.c
head: 1.8
branch:
72 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
locks: strict
access list:
symbolic names:
keyword substitution: kv
total revisions: 8;
selected revisions: 8
description:
The one and only source file for the trivial HTTP client
---------------------------revision 1.8
date: 1996/10/31 20:11:14;
lines: +1 -1
author: jimb;
state: Exp;
(tcp\_connection): Cast address structure when calling
connect.
---------------------------revision 1.7
date: 1996/10/31 19:18:45;
lines: +6 -2
author: fred;
state: Exp;
(match\_header): Make this test case-insensitive.
---------------------------revision 1.6
date: 1996/10/31 19:15:23;
lines: +2 -6
author: jimb;
state: Exp;
...
$
Most of the text here you can ignore; the portion to look at carefully is the
series of log entries after the first line of hyphens. The log entries appear in
reverse chronological order, under the assumption that more recent changes
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
73 of 171
are usually more interesting. Each entry describes one change to the file, and
may be parsed as follows:
‘revision 1.8’
Each version of a file has a unique revision number. Revision numbers look
like ‘1.1’, ‘1.2’, ‘1.3.2.2’ or even ‘1.3.2.2.4.5’. By default revision 1.1 is the first
revision of a file. Each successive revision is given a new number by increasing the rightmost number by one.
‘date: 1996/10/31 20:11:14; author: jimb; ...’
This line gives the date of the change, and the username of the person who
committed it; the remainder of the line is not very interesting. ‘(tcp connection):
Cast ...’ This (pretty obviously) is the log entry describing that change.
The cvs log command can select log entries by date range, or by revision
number; see the manual for details on this.
If you would actually like to see the change in question, you can use the
cvs diff command. For example, if you would like to see the changes Fred
committed as revision 1.7, you can use the following command:
$ cvs diff -c -r 1.6 -r 1.7 httpc.c
Before we look at the output from this command, let’s look at what the various parts mean:
-c
This requests that cvs diff use a more human-readable format for its output.
(I’m not sure why it isn’t the default.)
-r 1.6 -r 1.7
This tells CVS to display the changes needed to turn revision 1.6 of httpc.c
into revision 1.7. You can request a wider range of revisions if you like; for
example, -r 1.6 -r 1.8 would display both fred’s changes and your most recent
change. (You can even request that changes be displayed backwards —as if
they were being undone— by specifying the revisions backwards: -r 1.7 -r
1.6. This sounds odd, but it is useful sometimes.)
httpc.c
This is the name of the file to inspect. If you don’t give it specific files to
report on, CVS will produce a report for the entire directory.
Here is the output from the command:
Index: httpc.c
=======================================================
RCS file: /u/src/master/httpc/httpc.c,v
retrieving revision 1.6
74 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
retrieving revision 1.7
diff -c -r1.6 -r1.7
*** httpc.c
1996/10/31 19:15:23
1.6
--- httpc.c
1996/10/31 19:18:45
1.7
***************
*** 62,68 ****
\}
! /* Return non-zero iff HEADER is a prefix of TEXT.
!
HEADER should be null-terminated; LEN is the
!
length of TEXT.
*/
static int
match\_header (char *header, char *text, size\_t len)
--- 62,69 ---\}
! /* Return non-zero iff HEADER is a prefix of TEXT,
!
ignoring differences in case. HEADER should be
!
lower-case, and null-terminated; LEN is the
length of TEXT.
*/
static int
match\_header (char *header, char *text, size_t len)
***************
*** 76,81 ****
--- 77,84 ----
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
75 of 171
for (i = 0; i < header\_len; i++)
\{
char t = text[i];
+
if (’A’ <= t \&\& t <= ’Z’)
+
t += ’a’ - ’A’;
if (header[i] != t)
return 0;
\}
$
This output takes a bit of effort to get used to, but it is definitely worth understanding.
The interesting portion starts with the first two lines beginning with *** and
—; those describe the older and newer files compared. The remainder consists of two hunks, each of which starts with a line of asterisks. Here is the
first hunk:
***************
*** 62,68 ****
\}
! /* Return non-zero iff HEADER is a prefix of TEXT.
!
HEADER should be null-terminated; LEN is the
length of TEXT.
*/
static int
match\_header (char *header, char *text, size\_t len)
--- 62,69 ---\}
76 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
/* Return non-zero iff HEADER is a prefix of TEXT,
!
ignoring differences in case. HEADER should be
!
lower-case, and null-terminated; LEN is the
length of TEXT.
*/
static int
match\_header (char *header, char *text, size\_t len)
Text from the older version appears after the *** 62,68 *** line; text from the
new appears after the — 62,69 — line. The pair of numbers in each indicates the range of lines shown. CVS provides context around the change, and
marks the actual lines affected with ‘!’ characters. Thus, one can see that the
single line in the top half was replaced with the two lines in the bottom half.
Here is the second hunk:
***************
*** 76,81 ****
--- 77,84 ---for (i = 0; i < header\_len; i++)
\{
char t = text[i];
+
if (’A’ <= t \&\& t <= ’Z’)
+
t += ’a’ - ’A’;
if (header[i] != t)
return 0;
\}
This hunk describes the insertion of two lines, marked with ‘+’ characters.
CVS omits the old text in this case, because it would be redundant. CVS uses
a similar hunk format to describe deletions.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
77 of 171
Like the Unix diff command, output from cvs diff is usually called a patch,
because developers have traditionally used the format to distribute bug fixes
or small new features. While reasonably readable to humans, a patch contains enough information for a program to apply the changes it describes to
an unmodified text file. In fact, the Unix patch command does exactly this,
given a patch as input.
Adding and deleting files
CVS treats file creation and deletion like other changes, recording such events
in the files’ histories. One way to look at this is to say that CVS records the
history of directories as well as the files they contain.
CVS doesn’t assume that newly created files should be placed under its control; this would do the wrong thing in many circumstances. For example, one
needn’t record changes to object files and executables, since their contents can
always be recreated from the source files (one hopes). Instead, if you create
a new file, cvs update will flag it with a ‘?’ character until you tell CVS what
you intend to do with it.
To add a file to a project, you must first create the file, and then use the cvs
add command to mark it for addition. Then, the next call to cvs commit
will add the file to the repository. For example, here’s how you might add a
README file to the httpc project:
$ ls
CVS
Makefile
httpc.c
poll-server
$ vi README
... enter a description of httpc ...
$ ls
CVS
Makefile
README
httpc.c
poll-server
$ cvs update
cvs update: Updating .
? README --- CVS doesn’t know about this file yet.
$ cvs add README
cvs add: scheduling file ‘README’ for addition
cvs add: use ’cvs commit’ to add this file permanently
$ cvs update --- Now what does CVS think?
78 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
cvs update: Updating .
A README --- The file is marked for addition.
$ cvs commit README
... CVS prompts you for a log entry ...
RCS file: /u/jimb/cvs-class/rep/httpc/README,v
done
Checking in README;
/u/src/master/httpc/README,v
<--
README
initial revision: 1.1
done
$
CVS treats deleted files similarly. If you delete a file and then run cvs update,
CVS doesn’t assume you intend the file for deletion. Instead, it does something benign – it recreates the file with its last recorded contents, and flags it
with a ‘U’ character, as for any other update. (This means that if you want to
undo the changes you’ve made to a file in your working directory, you can
simply delete the files, and then let cvs update recreate them.)
To remove a file from a project, you must first delete the file, and then use the
cvs rm command to mark it for deletion. Then, the next call to cvs commit
will delete the file from the repository.
Committing a file marked with cvs rm does not destroy the file’s history. It
simply adds a new revision, which is marked as ”non-existent.” The repository still has records of the file’s prior contents, and can recall them as needed
– for example, by cvs diff or cvs log.
There are several strategies for renaming files; the simplest is to simply rename the file in your working directory, and run cvs rm on the old name,
and cvs add on the new name. The disadvantage of this approach is that the
log entries for the old file’s content do not carry over to the new file. Other
strategies avoid this quirk, but have other, stranger problems.
You can add directories just as you would ordinary files; Writing good log
entries
If one can use cvs diff to retrieve the actual text of a change, why should
one bother writing a log entry? Obviously, log entries can be shorter than
a patch, and allow the reader to get a general understanding of the change
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
79 of 171
without delving into its details.
However, a good log entry describes the reason the developer made the change.
For example, a bad log entry for revision 1.7 shown above might say, ”Convert t to lower-case.” This would be accurate, but completely useless; cvs diff
provides all the same information, more clearly. A better log entry would be,
”Make this test case-insensitive,” because it makes the purpose clear to anyone with a general understanding of the code: HTTP clients should ignore
case differences when parsing reply headers. Handling conflicts
As mentioned above, the cvs update command incorporates changes made
by other developers into your working directory. If both you and another
developer have modified the same file, CVS merges their changes with yours.
It’s straightforward to imagine how this works when the changes apply to
distant regions of a file, but what happens when you and another developer
have changed the same line? CVS calls this situation a conflict, and leaves it
up to you to resolve it.
For example, suppose that you have just added some error checking to the
host name lookup code. Before you commit your change, you must run cvs
update, to bring your sources into sync:
$ cvs update
cvs update: Updating .
RCS file: /u/src/master/httpc/httpc.c,v
retrieving revision 1.8
retrieving revision 1.9
Merging differences between 1.8 and 1.9 into httpc.c
rcsmerge: warning: conflicts during merge
cvs update: conflicts found in httpc.c
C httpc.c
$
In this case, another developer has changed the same region of the file you
have, so CVS complains about a conflict. Instead of printing ‘M httpc.c’, as
it usually does, it prints ‘C httpc.c’, to indicate that a conflict has occurred in
that file.
To resolve the conflict, bring up the file in your editor. CVS marks the conflicting text this way:
80 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
/* Look up the IP address of the host.
*/
host_info = gethostbyname (hostname);
<<<<<<< httpc.c
if (! host\_info)
\{
fprintf (stderr, "%s: host not found: %s\n",
progname, hostname);
exit (1);
\}
=======
if (! host\_info)
\{
printf ("httpc: no host");
exit (1);
\}
>>>>>>> 1.9
sock = socket (PF\_INET, SOCK\_STREAM, 0);
It’s important to understand what CVS does and doesn’t consider a conflict.
CVS does not understand the semantics of your program; it simply treats its
source code as a tree of text files. If one developer adds a new argument
to a function and fixes its callers, while another developer simultaneously
adds a new call to that function, and does not pass the new argument, that
is certainly a conflict – the two changes are incompatible – but CVS will not
report it. CVS’s understanding of conflicts is strictly textual.
In practice, fortunately, conflicts are rare. Usually, they seem to result from
two developers attempting to address the same problem, a lack of communication between developers, or disagreement about the design of the program.
Allocating tasks to developers in a reasonable way reduces the likelihood of
conflicts.
Many version control systems allow a developer to lock a file, preventing
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
81 of 171
others from making changes to it until she has committed her changes. While
locking is appropriate in some situations, it is not clearly a better solution
than the approach CVS takes. Changes can usually be merged correctly, and
developers occasionally forget to release locks; in both cases, explicit locking
causes unnecessary delays. Furthermore, locks prevent only textual conflicts;
they do not prevent semantic conflicts of the sort described above, if the two
developers make their changes to different files.
12.4
The ASLab CVS Repository
12.4.1
Location of the ASLab CVS Repository
The ASLab CVS repository is hosted in sagan (138.100.76.251) in the directory /home/cvsroot .
12.4.2
Use Politics
ASLab repository is intended for two main uses:
• Version Managing System, as commonly used, both for code and documents.
• To keep the sources for the group deliverables, any type they are.
12.4.3
Directory structure of ASLab CVS repository
The next figure shows the main directories in the repository.
The projects directories are organized as follows, taking the ICEA directory
as example.
The asys directory is a special case because, in addition to the common subdirectories of project directories, it has a subdirectory for each of the subprojects
that currently conform the asys vision.
Through the whole directory tree, at every level it may appear directories
with the following names and uses:
..\docs : for project documents.
..\figs : for relevant not formal diagrams.
..\models : for formal models(UML, SysML, . . . ).
..\code : for source code.
82 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
12.4.4
Using the ASLab CVS Repository
In a Unix Environment
To use the ASLab CVS server define the CVSROOT variable as follows (for
example in .bashrc):
export CVSROOT=:ext:username@tierra:/home/cvsroot
Where ’username’ stands for any accepted username in the CVS server.
With IBM eclipse based tools (RSA)
Go to Chapter Using RSA and CVS
12.5
Using CVS with an Eclipse Based Tool
12.6
CVS with RSD or Eclipse
It is possible to share a RSD project to allow other team members to access
it through ASLab CVS repository. The following subsections provide a basic
guide to use this tool, if you need more detailed help consult the EBT Help.
12.6.1
CVS configuration
To configure ASLab CVS repository in your RSD follow these instructions:
1. In the Model Explorer view, right click your project; then click Team →
Share Project
2. Select CVS Repository Exploring.
3. Now click on Add CVS Repository
4. Fill in the fields as shown in the figure ?? (substituting the user and
password with yours 1 )
5. Now you got it! You should see something like this in the CVS Repository exploring perspective.
1
if you do not have them ask ASLab’s Systems Administrator
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
83 of 171
Figure 12.1:
Figure 12.2:
Figure 12.3: Step 3
84 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
(a) Step 4
12.6.2
(b) Step 5
Sharing your projects
1. In the Model Explorer view, right-click your project; then click Team >
Share Project
Figure 12.4: Step 1
2. Select ASLab repository in the list and click Next:
3. Mark Use an existing module. . . , to select the directory in the repository where your project must be put:
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
85 of 171
Figure 12.5: Step 2
Figure 12.6: Step 3
86 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
4. Mark Use specified module name, to add the name of your project (we
do not recommend using a different name of that in your system for it
in the repository):
Figure 12.7: Step 4
5. Click Finish (if you checked to launch the commit wizard you will be
prompted another window, where you can enter a comment for your
commit or simply click Finish):
(a) Step 5
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
(b) Step 6
87 of 171
12.6.3
Working with projects from the repository
In this section we will explain how to check out a project from the repository and work with it locally in your computer, which will be the only thing
your usually do if you are not the system administrator or the development
manager.
Check Out
To work with a project from the repository the first step you have to take is
to check it out. This means to get a copy of the project in repository on your
local system.
1. In the CVS Repository Exploring perspective right click the directory
you want to check out as a project (figure 12.8).
2. Select Check Out.
Figure 12.8:
88 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
!!
If you are going to work with a project and keep it
synchronized with the repository, always perform a
Check Out and not a Check Out As.... The best
way not to mess up is to keep as few project in your
workspace as possible (just the projects your are currently working on).
If you are simply getting some useful sources from
the repository but you do not intend your change to
be on the repository, you can choose the Check Out
As... option.
In this case what is important is that you disconnect
your project from the repository so as not commit
undesired changes (see 12.6.3)
Now observe in the Resources perspective that the project has been added
to your workspace (figure 12.9(a)). The little yellow cylinder under the icon
of each file or directory within the project indicates that those resources are
synchronized (which does not mean currently updated) with the repository.
When there is a different between a local resource and the repository a “>”
appears preceding the name of the resource (see 12.9(b)):
(a) Step 5
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
(b) Step 6
89 of 171
Disconnect a project from the repository
1. Right click on the project you want to disconnet from the repository.
Select Team → Disconnect...
Figure 12.9: Step 1
2. Check Also delete the CVS metainformation...
Figure 12.10: Step1
90 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
12.7
Other reference material
12.7.1
Base documentation
Version Management with CVS by Per Cederqvist et al is the ”official” manual
for CVS. Commonly known as ”the Cederqvist,” the manual covers repositories, branches, and file maintenance, and includes reference material for
both CVS users and CVS repository administrators. This officially released
versions of this manual are available in several formats from web pages.
A recommended one is this version from the Ximbiot - CVS Wiki.
http://ximbiot.com/cvs/wiki/index.php?title =
CVS--Concurrent_Versions_System_v1.12.12.1
If you need other formats, the texinfo source file for the manual can be found
in the ‘doc’ directory of the CVS source distribution.
12.7.2
Other CVS Links
The CVS manual can be found at:
http://www.cvshome.org/docs/manual/
A web-based online CVS documentation can be found at:
http://ximbiot.com/cvs/manual/
http://cvsbook.red-bean.com/OSDevWithCVS_3E.pdf
12.8
Conclusions
It is good.
You should use it.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
91 of 171
Chapter 13
WindRiver Workbench
13.1
Introduction
WindRiver Linux
In this chapter we have collect information about Wind River General Purpouse Platform Linux Edition, Wind River’s version of Linux Operating System, adapted and packed for cross-compilation to a large diversity of platforms and embedded systems.
13.1.1
Wind River Workbench
Wind River Workbench in an Integrated Development Environment (IDE)
that permits development software for Linux embedded systems. Workbench is based on Eclipse’s platform – a common framework to develop Integrated Development Environments (IDE).
13.1.2
Wind River Linux
Wind River General Purpose Platform, Linux Edition, integrates closely with
Wind River Workbench 2.4, Linux Version, for both user mode and kernel
mode debugging:
• User mode – User mode debugging is enabled through the user mode
agent, which runs as a user process, getting its debug information via
the process trace (ptrace) API, an integral part of Linux kernel.
• Kernel mode – Kernel mode debugging is enabled through the KGDB
agent target boards. The KGDB agent (a kernel patch), allows a user
running GDB on a host machine to connect and perform kernel debugging on a target running the KGDB-patched kernel. Kernel mode
debugging takes place over a serial protocol connection which may be
over a serial line or Ethernet. The connection is typically over an NFS
92 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
mount. Kernel mode debugging can be performed either at a command
line (or Workbench console), or within the Workbench viewer.
• Dual Mode – This mode is only sopported in Linux kernel version 2.4,
and allows changing btween user mode and system (kernel) mode.
13.1.3
Installation in a host system
These are the disks required to install WindRiver GPP Linux in a host system:
• WindRiver Workbench 2.4
• WindRiver ScopeTools 5.4 (Optional)
• WindRiver GNU Compiler 3.4.4
• Cross Build System for GPP (Intel architecture)
• Reference Filesystem for GPP (Intel architecture)
• Reference Source
The Java Runtime Environment used by the setup program causes an error
because it can’t find a specific version of a dynamic library. The problem can
be resolved creating an appropiate symbolic link.
13.1.4
Installation in a target system
These are the steps neccesary to install WindRiver General Porpouse Platform, Linux Edition in a target system:
• Create a directory for the project:
mkdir /home/user/workspace/vaio tx2
• Run the configuration script to generate the construction environment:
$WINDRIVER/wrlinux-1.2/wrlinux/configure \
−−enable−platform=gpg −− enable−board=vaio tx2 \
−−enable−build=production −−config−cache −−enable−jobs=2
• Generate the runtime file system with:
make all (Source build method) or
make fs (RPM build method)
• Copy the kernel and file system generated in
/home/user/workspace/vaio tx2/export to the target, or, in case of
network booting, copy the kernel to a TFTP service (/tftpboot) and
copy the uncompressed system file to a directory shared with NFS.
It is possible to follow these steps guided by a menu. To follow the steps with
the menu you must generate a new project using the menu:
File → New → Wind River Linux Platform Project.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
93 of 171
13.2
WindRiver Linux BSP for GENE-6330
This section describes the add-ons realized to WindRiver Linux Platform in
order to use a GENE 6330 computer as target.
In order to use the WindRiver Linux Platform with the embedded system
GENE-6330 it has been neccesary to create a BSP (Board Support Package),
with a specific Linux kernel configuration for this machine and some RPM
packages to support the PCMCIA controller, the wireless LAN, ACE+TAO,
AROS, ARIA, etc.
13.2.1
BSP (Board Support Package): tm crusoe
The process to add a BSP for a new target is described in the manual “WindRiver General Purpose Platform, Linux Edition – Getting Started 1.2” in the
chapter, page 63. Following this process, a new BSP has been created in the
new directory:
$WINDRIVER/wrlinux-1.2/wrlinux/boards/tm crusoe
The environment variable WINDRIVER reference the installation path of WindRiver Platform in a concrete machine.
We will shortly examine some of the files in this directory:
The BSP contains two files with the kernel configuration for this system:
$WINDRIVER/wrlinux-1.2/wrlinux/boards/tm crusoe/knl-2.6.10.cfg
$WINDRIVER/wrlinux-1.2/wrlinux/boards/tm crusoe/gpp/knl-2.6.10.cfg
The file $WINDRIVER/wrlinux-1.2/wrlinux/boards/tm crusoe/pkglist.add
contains the names of the packages added to this BSP in order to support the
wireless LAN PCMCIA, ACE+TAO, AROS, ARIA, etc.
The files contained in
$WINDRIVER/wrlinux-1.2/wrlinux/boards/tm crusoe/fs are basic configuration files for the correct function of the system.
13.2.2
RPMs
To add support for the PCMCIA, the wireless LAN, CORBA, AROS, ARIA
and the server which controlls the robot in the GENE-6330 board it has been
neccesary to add some new RPM packages to this platform. These is the list
of new packages:
• GRUB (Updated)
• Lsof (Updated)
• Panicsel (Updated)
• Psmisc (Updated)
94 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
• Zebra (Updated)
• PCMCIA (PCMCIA support)
• Wireless-tools (Wireless utilities).
• ACE+TAO (CORBA broker)
• AROS (Robot firmware)
• ARIA (Robot libraries)
• SQLite (Database)
• HiggsOpServer (Robot control software)
• Higgstest (Robot test software)
In the manual “WindRiver General Purpose Platform, Linux Edition – Getting Started 1.2”, already mentiones, is described the process to add new
packages to WindRiver Linux Platform in chapter 5, page 51. This process
contains six steps. These are the steps:
• Install the compressed source code of the package.
• Create the directories of the package.
• Create a Makefile.
• Add the package to the corresponding template.
• Unpackage and build the RPM package.
• Add the RPM package to the development environment.
This list contains the names of the compressed source code of these packages:
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/pcmcia-cs-3.2.8.tar.gz
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/wireless tools.28.tar.gz
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/ACE-5.4.6.tar.bz2
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/ACE-5.4.6+TAO-1.4.6.tar.bz2
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/AROS-1.13.tgz
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/ARIA-2.4.3.tgz
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/higgs-1.0.tar.gz
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/higgstest-1.0.tar.gz
The directories and corresponding Makefiles are:
$WINDRIVER/wrlinux-1.2/wrlinux/dist/pcmcia-cs
$WINDRIVER/wrlinux-1.2/wrlinux/dist/wireless-tools
$WINDRIVER/wrlinux-1.2/wrlinux/dist/tao
$WINDRIVER/wrlinux-1.2/wrlinux/dist/aros
$WINDRIVER/wrlinux-1.2/wrlinux/dist/aria
$WINDRIVER/wrlinux-1.2/wrlinux/dist/higgs
$WINDRIVER/wrlinux-1.2/wrlinux/dist/higgstest
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
95 of 171
13.3
WindRiver Linux BSP for Vaio TX2HP
This section describes the add-ons realized to WindRiver Linux Platform in
order to use a VAIO TX2HP computer as target.
In order to use the WindRiver Linux Platform with SONY’s VAIO TX2HP
computer, it has been neccesary to create a BSP (Board Support Package),
with a specific Linux kernel configuration for this machine and four RPM
packages to support the wireless LAN of this machine.
13.3.1
BSP (Board Support Package): vaio tx2
The process to add a BSP for a new target is described in the manual “WindRiver General Purpose Platform, Linux Edition – Getting Started 1.2” in the
chapter, page 63. Following this process, a new BSP has been created in the
new directory:
$WINDRIVER/wrlinux-1.2/wrlinux/boards/vaio tx2
The environment variable WINDRIVER reference the installation path of WindRiver Platform in a concrete machine.
We will shortly examine some of the files in this directory:
The BSP contains two files with the kernel configuration for this system:
$WINDRIVER/wrlinux-1.2/wrlinux/boards/vaio tx2/knl-2.6.10.cfg
$WINDRIVER/wrlinux-1.2/wrlinux/boards/vaio tx2/gpp/knl-2.6.10.cfg
The file $WINDRIVER/wrlinux-1.2/wrlinux/boards/vaio tx2/pkglist.add contains the names of the packages added to this BSP in order to support the
wireless LAN PCMCIA.
The files contained in
$WINDRIVER/wrlinux-1.2/wrlinux/boards/vaio tx2/fs are basic configuration files for the correct function of the system.
13.3.2
RPMs
To add support for the wireless LAN Intel IPW2200 to the computer VAIO
TX2 it has been neccesary to add four RPM packages to this platform. These
is the list of new packages:
• Wireless-tools (Wireless utilities).
• IEEE80211 (Net protocol stack).
• IPW2200 (Network drivers).
• IPW2200-FW (Firmware).
96 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
In the manual “WindRiver General Purpose Platform, Linux Edition – Getting Started 1.2”, already mentiones, is described the process to add new
packages to WindRiver Linux Platform in chapter 5, page 51. This process
contains six steps. These are the steps:
• Install the compressed source code of the package.
• Create the directories of the package.
• Create a Makefile.
• Add the package to the corresponding template.
• Unpackage and build the RPM package.
• Add the RPM package to the development environment.
This list contains the names of the compressed source code of these packages:
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/wireless tools.28.tar.gz
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/ieee80211-1.1.13.tgz
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/ipw2200-1.1.0.tgz
$WINDRIVER/wrlinux-1.2/wrlinux-pkgs/ipw2200-fw-2.4.tgz
The directories and corresponding Makefiles are:
$WINDRIVER/wrlinux-1.2/wrlinux/dist/ipw2200
$WINDRIVER/wrlinux-1.2/wrlinux/dist/wireless-tools
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
97 of 171
Chapter 14
GCC
http://gcc.gnu.org/
GCC is the acronym of GNU Compiler Collection. The GNU Compiler Collection includes front ends for C, C++, Objective-C, Fortran, Java, and Ada,
as well as libraries for these languages (libstdc++, libgcj,...).
14.1
CPP - The Preprocessor
CPP is the Preprocessor used to parse som directives before the compilation
stage. It i used in C, C++ and Objective-C, although it can also be optionally
used with Java or Ada.
The Directives Understood by the GNU Preprocessor
98 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Directive
#define
#elif
#else
#error
#if
#ifdef
#ifndef
#include
#include next
#line
#pragma
#undef
#warning
##
Description
Defines a name as a macro that the preprocessor will expand
in the code every place the name is used.
Provides an alternative expression to be evaluated by an
#if directive.
Provides an alternative set of code to be compiled if an
#if, #ifdef, or #ifndef is false.
Produces an error message and halts the preprocessor.
Compiles the code between this directive and its matching
#endif only if evaluating an arithmetic expression results
in a nonzero value.
Compiles the code between this directive and its matching
#endif only if the named macro has been defined.
Compiles the code between this directive and its matching
#endif only if the named macro has not been defined.
Searches through a list of directories until it finds the named
file; then it inserts the contents of the file just as if it had been
inserted by a text editor.
The same as #include, but this directive begins the search
for the file in the directory following the one in which the
current file was found.
Specifies the line number, and possibly the file name, that
is reported to the compiler to be used to create debugging
information in the object file.
A standard method of providing additional information
that may be specific to one compiler or one platform.
Removes a definition previously created by a #define
directive.
Produces a warning message from the preprocessor.
The concatenation operator, which can be used inside
a macro to combine two strings into one.
The following command shows the predefined set of macros of the compiler:
gcc -dM -E - < /dev/null
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
99 of 171
The Basic Set of Predefined Macros
Macro
Description
BASE FILE
A quoted string containing the full path
name of the source file specified on the
command line (not necessarily the file
in which the macro is used). Also see
FILE .
CHAR UNSIGNED
This macro is defined to indicate that the
char data type is unsigned on the target
machine. This is used by limits.h to
determine the values of CHAR MIN and
CHAR MAX.
cplusplus
Defined only when the source code is a C++
program. It is defined as 1 if the compiler
does not fully conform to a standard;
otherwise, it is defined with the month
and year of the standard in the same
manner as STDC VERSION for C.
DATE
An 11-character quoted string containing
the date the program was compiled. It
has the form ”May 3 2002”.
FILE
A quoted string containing the name of the
source file in which the macro is used. Also
see BASE FILE .
func
The same as FUNCTION .
FUNCTION
A quoted string containing the name of the
current function.
GNUC
This macro is always defined as the major
version number of the compiler. For example,
if the compiler version number is 3.1.2, this
macro is defined as 3.
GNUC MINOR
This macro is always defined as the minor
version number of the compiler. For example,
if the compiler version number is 3.1.2, this
macro is defined as 1.
GNUC PATCHLEVEL
This macro is always defined as the revision
level of the compiler. For example, if the
compiler version number is 3.1.2, this macro
is defined as 2.
GNUG
Defined by the C++ compiler. This macro is
defined whenever both cplusplus and
GNUC
are also defined.
INCLUDE LEVEL
An integer value specifying the current depth
level of the include file. The value at the
base file (the one specified on the command
line) is 0 and is increased by 1 inside each file
input by an #include directive.
100 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
LINE
NO INLINE
OBJC
OPTIMIZE
OPTIMIZE SIZE
REGISTER PREFIX
STDC
STDC HOSTED
STDC VERSION
STRICT ANSI
TIME
USER LABEL PREFIX
USING SJLJ EXCEPTIONS
VERSION
The line number of the file in which the
macro is used.
This macro is defined as 1 when no functions
are to be expanded inline, either because
there is no optimization or inlining has
been specifically disabled.
This macro is defined as 1 if the program is
being compiled as Objective-C.
This macro is defined as 1 whenever any
level of optimization has been specified.
This macro is defined as 1 if optimization is
set for size instead of speed.
This macro is a token (not a string) that is
the prefix for register names. It can be used
to write assembly language that’s portable to
more than one environment.
Defined as 1 to indicate that the compiler is
conforming to standard C. This macro is not
defined when compiling C++ or Objective-C,
and it is also not defined when the
-traditional option is specified.
Defined as 1 to signify a ”hosted”
environment (one that has the complete
standard C library available).
A long integer specifying the standards
version number in terms of its year and
month. For example, the 1999 revision of the
standard is the value 199901L. This macro
is not defined when compiling C++ or
Objective-C, and it is also not defined when
the -traditional option is specified.
Defined if and only if either -ansi or -std
has been specified on the command line. It is
used in the GNU header files to restrict the
definitions to those defined in the standard.
A seven-character quoted string containing
the time the program was compiled. It has
the form ”18:10:34”.
This macro is a token (not a string) that is
used as the prefix on symbols in assembly
language. The token varies depending on
the platform, but it’s usually an underscore
character.
This macro is defined as 1 if the mechanism
for handling exceptions is setjmp
and longjmp.
The complete version number. There is no
specific format for this information, but it
will at least include the major and minor
release numbers.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
101 of 171
14.2
GCC - Compiling C
File Name Suffixes in C Programming
Suffix File Contains
.a
Static object library (archive).
.c
C source code that is to be preprocessed.
.h
C source code header file.
.i
C source code that is not to be preprocessed.
produced as an intermediate step in compilation.
.o
An object file in a format appropriate to
This type of file is produced as an intermediate
.s
Assembly language code. This type of
intermediate step in compilation.
.so
Shared object library.
Options Controlling the C Language Version
Option
Description
-ansi
Compiles programs that are standards compliant as well as
the GNU extensions
-pedantic
Issues warnings required by strict standards compliance
-std=c89
The ISO C89 standard
-std=c99
The ISO C99 standard
-std=gnu89 The ISO C89 standard with GNU extensions and some
C99 features
-traditional Compiles with the original C syntax
Attributes That Can Be Used in Function Declarations
Attribute
Description
alias
A function definition with this attribute causes the definition
to become a weak alias of another function. It can be used in
combination with the weak attribute to define a weak alias, as
in the following example, where centon() is created as a weak
alias for centon():
int centon() return(100);
void centon() attribute
((weak,alias(” centon”)));
In C++ the mangled name of the target must be specified. This
attribute is not supported on all machines.
always inline A function that’s declared as being inline, and has this attribute,
will always be expanded as inline code, even when no optimization
has been specified. Normally functions are only inlined during
optimization. The following is an example of the prototype
of a function that will always be expanded inline:
inline void infn() attribute ((always inline));
102 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Attribute
const
constructor
deprecated
destructor
format
format arg
Description
A function with this attribute is the same as pure, but it also does
not read any values from global memory. This gives the optimizer
more freedom than pure because there is no need to make certain
that all global values are updated before the function is called.
A function with this attribute is called automatically before the
call is made to main(). Also see the destructor attribute.
A function with this attribute will cause the compiler to issue
a warning message whenever it is called. The warning message
includes the location of the deprecated function to guide the user
to more information about it.
A function with this attribute is called automatically after main()
has returned or exit() has been called. Also see the
constructor attribute.
A function with this attribute has one argument that is a format
string and a variable number of arguments for the values to be
formatted. This makes it possible for the compiler to check the
format content against the list of arguments to verify that the types
match the formatting. There are different types of formatting, so it is
also necessary to specify whether validation is to be for the printf,
scanf, strftime, or strfmon style. For example, the following
attribute specifies that the second argument passed to the function is
the formatting string, the formatting string is expected to be of the
printf type, and the variable-length argument list begins with
the third argument:
int logprintf(void *log, char *fmt, ...)
attribute ((format(printf,2,3)));
Warning messages are issued when a format string is found to be
invalid only if the -Wformat option is specified.
A function with this attribute accepts a formatting string as one
of its arguments and makes a modification to the string so that the
result can be passed on to a printf(), scanf(), strftime(),
or strfmon() type function. This attribute will suppress warning
messages issued when the option -Wformat-nonliteral is set
to detect nonconstant formatting strings. The following example
demonstrates the setting of this attribute for a function that has
such a format string as its second argument:
void fedit(int ndx,const char *fmt)
attribute ((format arg(2)));
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
103 of 171
Attribute
malloc
no instrument
function
noinline
noreturn
pure
section
used
weak
104 of 171
Description
A function with this attribute informs the compiler that it can
be treated as if it were the malloc() function. For purposes of
optimization, the compiler is to assume the returned pointer
cannot alias anything.
A function with this attribute will not be instrumented and
will not have profiling code inserted into it by the compiler, even
if the -finstrument-functions option is set.
A function with this attribute will never be expanded as inline code.
A function with this attribute does not return to its caller.
A function with this attribute has no side effects whatsoever, except
with respect to its return value. That is, there will be no changes
global values, locations addressed by arguments, or the contents
of files. Unlike the const attribute, this function may read global
values. This makes it possible for the compiler to perform common
subexpression optimization because all the values are guaranteed
to be stable.
A function with this attribute will have its assembly language
code placed into the named section instead of the default text
section. The following is an example of a function being put
into a section named specials:
void mspec(void) attribute ((section(”specials”)));
This attribute will be ignored on systems that do not support
sectioning. Also see -ffunction-sections in Appendix D.
A function with this attribute causes the compiler to generate code
for the function body, even if the compiler determines the function
is not being used. This can be useful for functions that are called
only from inline assembly.
A function with this attribute has its name emitted as a weak
symbol instead of a global name. This is primarily for the naming
of library routines that can be overridden by user code.
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Attributes That Can Be Used in Data Declarations
Attribute
Description
aligned
A variable with this attribute is aligned on a memory address that is
an even multiple of the number specified for the alignment. For example,
the following declaration will align alivalue at a 32-bit address:
int alivalue attribute ((aligned(32)));
Alignment can be convenient on some systems to accommodate certain
assembly language instructions. It can also be useful with fields in
a struct that need to accommodate the data format found in a file.
If no alignment number is specified, the compiler will align the item
to the largest alignment used for any data item for the hardware, as in
the following example:
short shlist[312] attribute ((align));
deprecated A variable with this attribute will cause the compiler to issue a
warning every place it is referenced.
mode A variable with this attribute is sized to match the size of the
specified mode. The mode can be set to byte, word, or pointer. The mode
attribute determines the data type. For example, the following creates
an int that is the size of a single byte:
int x attribute ((mode(byte)));
nocommon A variable with this attribute is not allocated as common but is
instead allocated its own space. The variable is provided with an initial
value of all zeroes. Specifying the command-line option -fno-common
will cause this attribute to be applied to all variables.
packed
A variable with this attribute has the smallest possible alignment. A
variable will be separated no more than one byte from its predecessor
field. In a struct, a field with this attribute will be allocated with no
space between it and the field before it. For example, in the following
struct, the start of the array named zar is aligned exactly one byte
from the top of the struct:
struct zrecord {
char id;
int zar[32] attribute ((packed));
};
Also see the options -fpack-struct and -Wpacked in Appendix D.
section
A variable with this attribute will be placed into the named section
instead of the default data or bss section. The following is an example
of a function being put into a section named domx:
struct domx attribute ((section(”domx”))) = 0 ;
int trigger attribute ((section(”MONLOG”))) = 0;
Because of the way the linker handles data, data declared in its own
section must have initial values. This attribute will be ignored on
systems that do not support sectioning. Variable initialization can
be forced by the command-line option -fno-common.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
105 of 171
Attribute
unused
vector size
weak
14.3
Description
A variable with this attribute tells the compiler that the variable may
not be used, and no warning should be issued.
A variable with this attribute is allocated the total amount of
space specified as the size of the vector.
For example, the following declares a vector of float data types:
float fvec attribute ((vector size(32));
Assuming a float data type is 4 bytes long, this declaration creates
a block containing 8 float variables for a total size of 32 bytes.
This attribute is only valid for integer and real scalars.
A variable with this attribute has its name emitted as a weak symbol
instead of as a global name. This is primarily for the naming of library
variables that can be overridden by user code.
G++ - Compiling C++
File Name Suffixes in C++ Programming
Suffix
File Contains
.a
Static object library (archive file).
.C, .c++,
C++ source code that is to be preprocessed.
.cc, .cp,
.cpp, .cxx
.h
C or C++ header file.
.ii
C++ source code that is not to be preprocessed.
produced as an intermediate step in compilation.
.o
An object file in a format appropriate to
This type of file is produced as an intermediate
.s
Assembly language source code. This
an intermediate step in compilation.
<none> The standard C++ system header files
106 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
The Attributes Defined for the C++ Language
Attribute
Description
init priority
Standard C++ specifies that objects be initialized in the order
in which they appear within a compilation unit, but there is
no specification for the order across compilation units. The
init priority
attribute makes it possible to specify the
order of object initialization within a given namespace by
assigning priority numbers to the object declarations.The
priorities are assigned numerically, with the smaller numbers
having priority over larger numbers. For example, the
following three objects will be initialized in the order B, then
C, then A, no matter what source modules they are found in:
SpoClass A attribute ((init priority(680)));
SpoClass B attribute ((init priority(220)));
SpoClass C attribute ((init priority(400)));
The values used have no particular meaning, except in the
way they relate to one another.
java interface This attribute specifies that the class is to be defined as
a Java interface. It can only be applied to classes defined
inside an extern ”Java” block. Calls to methods of a class
defined this way use the GCJ interface table instead of the
C++ virtual table.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
107 of 171
Code Letters Used in Name Mangling
Code
Meaning
Letter
<number> The number of characters in a custom data type name. For example,
the function Mph::pdq(char, drip, double) encodes as
pdq 3Mphc4dripd. Optionally, the number can be preceded
by the letter G-that is, pdq 3Mph4drip is equivalent to
pdq 3MphG4drip.
A
An array. In C++ the arrays always decay to pointers, so this type
is never actually seen. In Java, an array is encoded as a pointer to
a
JArray type.
b
A C++ bool data type or a Java boolean data type.
c
The C++ char data type or the Java byte data type.
C
A modifier indicating a const parameter type or member function.
d
The double data type.
e
Extra arguments of unknown types. For example, the function
Mph::pdq(int,. . . ) encodes as pdq 3Mphie.
f
The float data type.
G
See <number>.
H
A template function.
i
The int data type.
I
A special integer data type containing a nonstandard number of
bits. For example, the function Mph::pdq(int, int60 t, char)
with a 60-bit integer type as its second argument will be encoded
as pdq 3MphiI 3C c. A hexadecimal number surrounded by
underscore characters is used to specify the number of bits in the
integer. The hexadecimal number may not be delimited by underscore
characters if the surrounding characters are not ambiguous.
J
The C++ complex data type.
l
(ell) The C++ long data type.
L
The name of a local class.
108 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Code
Letter
p
P
Q
r
R
s
S
S
t
T
u
U
v
V
w
x
X
Y
Meaning
A pointer. It is always followed by an indicator of the pointer type.
Same as P.
A pointer. It is always followed by an indicator of the pointer type.
Same as p.
A qualified name, such as arises from a nested class.
The C++ long double data type.
A C++ reference. It is always followed by an indicator of the type
being referenced. For example, the function Mph::pdq(ostream&)
is encoded as pdq 3MphR7ostream.
The short data type.
If S is used to precede the name of a class, it implies static. For
example, Mph::pdq(void) static is encoded pdq S3Mph. If
is used to precede a char data type indicator, it implies signed.
For example, the function Mph::pdq(signed char) is encoded
pdq 3MphSc.
A C++ template instantiation.
A back reference to a previously seen parameter type.
The type qualifier for a restricted pointer.
A modifier indicating an unsigned integer data type. It is also
used as a modifier for a class or namespace name to indicate
Unicode encoding.
The void data type.
A modifier indicating a volatile data type.
The C++ whcar t data type or the Java char data type.
The C++ long long data type or the Java long data type.
A template type parameter.
A template constant parameter.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
109 of 171
14.4
GNAT - Compiling Ada
File Name Suffixes in Ada Programming
Suffix File Contains
.a
A library (archive file) containing object files for static linking.
.adb
An Ada body file, which is source code containing a library unit body.
.adc
AGNAT configuration file for dead code elimination.
.ads
An Ada spec file, which is source code containing
declaration or a library unit renaming a declaration.
.adt
AGNAT tree file for dead code elimination.
.ali
An intermediate file that is produced by the compiler
information necessary for consistency checks and
.atb
A file containing a representation of the internal tree
compiler to represent the content of an .adb file.
.ats
A file containing a representation of the internal tree
compiler to represent the content of an .ads file.
.o
An object file in a format appropriate to be supplied
.s
Assembly language code. This type of file is produced
intermediate step in creating the object file.
.so
A library containing object files for dynamic linking.
14.5
GFORTRAN - Compiling Fortran
File Name Suffixes in Fortran Programming
Suffix
File Contains
.a
Static object library (archive)
.f, .for, .FOR Fortran source code that is not to be preprocessed
.F, .fpp, .FPP Fortran source code that is to be preprocessed
.o
An object file in a format appropriate to be fed to the linker
.r
Fortran source code to be preprocessed by Ratfor
.so
Shared object library
Options Used to Specify Upper and Lower Case Requirements
Keyword
Intrinsic
Symbol
-fmatch-case-any
-fintrin-case-any
-fsymbol-case-any
-fmatch-case-upper -fintrin-case-upper -fsymbol-case-upper
-fmatch-case-lower
-fintrin-case-lower
-fsymbol-case-lower
-fmatch-case-initcap -fintrin-case-initcap -f symbol-case-initcap
The Four Possible Case Requirements
110 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Option
any
upper
lower
initcap
Description
There is no restriction on specifying case, and all combinations
will match. For example, Function, FUNCTION, function,
and FuncTion are all the same.
All characters must be uppercase.
All characters must be lowercase.
The initial letter must be uppercase and all other letters must be
lowercase. For example, Maximum, Function, Do, and Return.
Control of Case Output to the Assembler
Option
Description
-fsource-case-preserve The output in the assembly language is in the
same case as the input to the compiler.
-fsource-case-upper
All symbols output in the assembly language
are converted to uppercase.
-fsource-case-lower
All symbols output in the assembly language
are converted to lower case.
Single Options That Specify Input and Output Case Combinations
Option
Description
-fcase-initcap
This option requires that everything begin
with initial capital letters, except comments and
character constants. This is the same as specifying
all three initcap options from Table 7-2 and also
specifying -fsource-case-preserve.
-fcase-lower
This is the “canonical” UNIX model where all
source is translated to lowercase. This is the same
as specifying all three any options from Table 7-2
and also specifying -fsource-case-lower.
-fcase-preserve
This option allows any case input pattern, and
the input case is preserved in the output assembly
language. This is the same as specifying all three
any options from Table 7-2 and also specifying
-fsource-case-preserve.
-fcase-strict-upper This is the strict ANSI FORTRAN 77 requirement
that everything be in uppercase, except comments
and character constants. This is the same as
specifying all three upper options from Table 7-2
and also specifying -fsource-case-preserve.
-fcase-strict-upper This option requires that everything be in lowercase
except comments and character constants. This is
the same as specifying all three lower options from
Table 7-2 and also specifying
-fsource-case-preserve.
-fcase-upper
This is the “classic” ANSI FORTRAN 77 model
where all source is translated to uppercase. This is
the same as specifying all three any options from
Table 7-2 and also specifying -fsource-case-upper.
Alternative Characters for the Original Comparison Operators
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
111 of 171
Original
.GT.
.LT.
.GE.
.LE.
.NE.
.EQ.
Alternative
>
<
>=
<=
/=
==
Means
Greater than
Less than
Greater than or equal to
Less than or equal to
Not equal to
Equal to
The Numbers Defined for the KIND Notation
KIND Value Description
0
This value currently has no effect but is reserved for future use.
There are plans to have the resulting type be context sensitive
and adjust its semantics depending on how it is used.
1
This is the default setting. The result is the same as if no KIND
value had been specified. This is typically REAL*4, INTEGER*4,
LOGICAL*4, and COMPLEX*8.
2
These types occupy twice the space of the default. In GNU,
variables of this KIND are equivalent to the Fortran 90 standard
for double precision. That is, REAL(KIND=2) is equivalent to
DOUBLE PRECISION, which, in turn, is typically REAL*8. Also,
COMPLEX(KIND=2) is equivalent to DOUBLE COMPLEX, which,
in turn, is typically COMPLEX*16.
INTEGER(KIND=2) and LOGICAL(KIND=2) are not supported
on every GNU implementation.
3
These types occupy as much space as a single
CHARACTER(KIND=1) type. These are typically INTEGER*1
and LOGICAL*1. This KIND is not necessarily implemented for
all types on all GNU implementations.
5
These types occupy half as much space as the default type
(as specified by KIND=1). These are typically INTEGER*2
and LOGICAL*2. This KIND is not necessarily implemented
for all types on all GNU implementations.
7
This is valid only for INTEGER(KIND=7) and is the same
size as the smallest possible pointer that can hold a unique
address of a CHARACTER*1 variable. On a 32-bit system, this
is equivalent to INTEGER*4, while on a 64-bit system it is
equivalent to INTEGER*8.
112 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
14.6
GCJ - Compiling Java
File Name Suffixes in Java Programming
Suffix File Contains
.a
A library (archive file) containing object files for static linking
.class An object file containing bytecodes in a format that can be executed
by a Java Virtual Machine
.java
Java source code
.o
A binary object file in a format appropriate to be supplied to a linker
.s
Assembly language source code
.so
A shared library containing object files for dynamic linking
The Command-Line Options Available for gij
Option
Description
-Dname[=value] The name becomes a defined system property name with
the specified value. If the value is omitted, the name is
defined with a value of a zero-length string.
–help
Prints this list of options and quits.
-jar
The name on the command line is interpreted as the name
of a jar file instead of a class file.
-ms=number
The number is the initial size of the heap.
-mx=number
The number is the maximum size of the heap.
–version
Prints the version number of gij and quits.
The Command-Line Options of jar
Option
Description
-@
Reads the list of files named from standard input.
-c
Creates a new jar file.
-C
dir file Retrieves the file named file from the directory named dir.
-E
dir Specifies that no files from the directory named dir are to
be included.
-f
file The named file is the jar file.
–help
Prints this list of options and some other brief help information.
-m
file The named file is a file containing manifest information to
be included.
-M
Specifies that no manifest file is to be created.
-O
Stores the files in the jar file without using compression.
-t
Lists the contents of the jar file.
-u
Updates an existing jar file.
-v
Displays verbose output to standard output describing the
actions being taken.
-V
Same as –version.
–version Displays the version number of the jar utility.
-x
Extracts files from a jar file.
The Command-Line Options of gcjh
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
113 of 171
Option
-add
-append
–bootclasspath=path
–classpath=path
–CLASSPATH=path
-d
-friend text
–help
-Idirectory
Description
text Inserts the specified text into the C++ class body.
This option is ignored if -jni is specified.
text Inserts the specified text into the header file
following the C++ class declaration. This option
is ignored if -jni is specified.
Overrides the built-in classpath.
Specifies the path to be used to locate class files.
Specifies the path to be used to locate class files.
directory Specifies the output directory name.
Inserts the specified text into the C++ class
definition as a friend declaration. This option
is ignored if -jni is specified.
Lists the options in this table to standard output.
Appends the specified directory onto the end of
the classpath.
Table 8-4. The Command-Line Options of gcjh (continued)
Option
Description
-M
Suppresses normal output and prints all
dependencies to standard output.
-MD
Prints all dependencies to standard output.
-MM
Suppresses normal output and prints non-system
dependencies to standard output.
-MMD
Prints non-system dependencies to standard output.
-o
file Specifies the name of the output file. This option
will produce an error if more than one file is to
be output.
-prepend text Inserts the specified text into the header file before
the C++ class declaration. This option is ignored
if -jni is specified.
-stubs
Stub files are generated instead of header files.
The stub file has the same base name as the class
but with the file suffix .cc. If -jni is also specified,
the suffix is .c.
-td directory
The name of the directory to use for temporary files.
-v
Prints extra information during processing.
Same as –verbose.
–verbose
Prints extra information during processing.
Same as -v.
–version
Prints the version number and exits.
The Command-Line Options for jcf-dump
114 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Option
–bootclasspath=path
-c
–classpath=path
–CLASSPATH=path
–help
-Idirectory
Description
Overrides the built-in classpath setting.
Disassembles the bytecodes of the method bodies.
Specifies the path to be used to locate class files.
Specifies the path to be used to locate class files.
Prints this list of options and exits.
Appends the specified directory onto the end of
the classpath.
The Command-Line Options for jcf-dump (continued)
Option
Description
–javap
Generates the output in the same format as javap.
The program javap is provided as part of the
standard Sun Microsystems Java distribution.
-o file
Directs the output to the named file instead of to
standard output.
-v
Prints extra information during processing.
Same as –verbose.
–verbose Prints extra information during processing.
Same as -v.
–version Prints the version number and exits.
The Command-Line Options for jv-scan
Option
Description
–complexity
Prints the cyclomatic complexity value of each class.
The number is calculated by analyzing the control flow
as a directed graph and counting the nodes, edges, and
the number of connected components.
–encoding=name Specifies the encoding name of the particular character
set to be used when reading the source. If a locale name
is set, it is used; otherwise, UTF-8 is assumed.
The Command-Line Options for jv-scan (continued)
Option
Description
–help
Prints this list of options and exits.
–list-class
Prints the names of the classes found in all the files on
the command line.
–list-filename When used in conjunction with –list-class, the
file name containing each class is also listed.
-o file
The output is directed to the named file instead of to
standard output.
–print-main
Prints the names of the classes containing a public
static void main() method.
–version
Prints the version number and exits.
Command-Line Options for jv-convert
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
115 of 171
Option
–encoding
–from name
–help
-i file
-o file
–reverse
-to name
\uXXXX
–version
Description
name The name of the encoding scheme of the input data.
The default is the local computer’s locale encoding.
Same as –from.
The name of the encoding scheme of the input data.
The default is the local computer’s locale encoding.
Same as –encoding.
Prints this list of options.
The name of the input file.
The name of the output file.
Reverses the specified –from and –to encodings.
The name of the encoding scheme of the output data.
The default is JavaSrc, which is ASCII text with Java
hexadecimal encoding for non-ASCII characters.
Prints the version number of jv-convert.
Character Encodings Known to jv-convert
Encoding Name Description
8859 1
ISO-Latin-1 (8851-1) text.
ASCII
The standard ASCII character set.
EUCJIS
Extended UNIX Code for Japan.
JavaSrc
The standard ASCII character set with
hexadecimal \uXXXX encoding for
SJIS
Shift JIS, which is used on Japanese
UTF8
A form of encoding Unicode characters
ASCII
characters as 8-bit entities.
Command-Line Options for grepjar
Option
Description
-b
Prints the byte offset into the file of the match.
-c
Prints the number of matches found instead of printing each
individual match.
-e
This option can be used to specify the pattern to be matched,
if the position on the command line does not make it clear.
–help
Prints this list of options.
-i
Ignores case when determining a match.
-n
Prints the line number in the file for each match.
-s
Suppresses the printing of error messages.
–version Prints the version number of grepjar.
-w
Specifies that the regular expression pattern only match
full words.
Command-Line Options for rmic
116 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Option
-classpath path
-d directory
-depend
-g
-help
-J flag
-keep
Description
The classpath to use for locating referenced classes.
The name of the directory to contain the generated stub
and skeleton files.
Checks dependencies and recompiles any files that are
out of date.
Includes debugging information in the generated files.
Prints this list of options.
Passes the specified flag to the Java compiler for
compilation of the stub and skeleton classes.
Retains the intermediate files instead of deleting them.
Same as -keepgenerated.
Command-Line Options for rmic (continued)
Option
Description
-keepgenerated Retains the intermediate files instead of deleting them.
Same as -keep.
-nocompile
Specifies not to compile the generated stub and skeleton
source files into class files.
-nowarn
Suppresses warning messages.
-v1.1
Generates stubs for Java 1.1.
-v1.2
Generates stubs for Java 1.2.
-vcompan
Generates stubs for both Java 1.1 and Java 1.2.
-verbose
Prints descriptions of the steps taken to produce the stub
and skeleton files.
-version
Prints the version number of the rmic compiler.
Command-Line Options for rmiregistry
Option
Description
–help
Prints this list of options and exits.
–version Prints the current version number of rmiregistry and exits.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
117 of 171
Chapter 15
Java Development Kit
15.1
Java
Java es un lenguaje orientado a objetos, interpretado, y diseñado desde su
s orı́genes para ser usado en aplicaciones distribuidas y ser portable entre
plataformas. La portabilidad de Java se fundamenta en el concepto de máquina
virtual. Todo el software Java se ejecuta, teóricamente, sobre la misma plataforma
software, la máquina virtual de Java (JVM), que se asienta sobre el sistema operativo.
Inicialmente Sun llamó a las Librerı́as de Clases y a la Máquina Virtual de
Ja va (JVM) con el nombre Java Development Kit (JDK). En 1999, el JDK fue
extendido y renombrado como Java 2 Platform. Existen diferentes versiones
de la plataforma, dependiendo de la aplicación, para clientes, servidores o
dispositivos móbiles. La plataforma Java más popular es J2EE, Java 2 Platform Entreprise Edition ver figura 15.1, que es una ampliación de J2SE, Java 2
Platform Standard Edition figura 15.2.
15.2
Programas del JDK
• java - the Java application launcher
• appletviewer - The Java Applet Viewer
• apt - annotation processing tool
• javac - the Java programming language compiler
• javap - The Java Class File Disassembler
• jconsole - Java Monitoring and Management Console
• jps - Java Virtual Machine Process Status Tool
• jsadebugd - Serviceability Agent Debug Daemon
118 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Figure 15.1: Diagrama de la plataforma J2EE5
Figure 15.2: Diagrama de la plataforma J2SE5
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
119 of 171
• jdb - Java Application Debugger
• jhat - Java Heap Analysis Tool
• jmap - Memory Map
• jinfo - Configuration Info
• javah - C Header and Stub File Generator
• jar - JAR Archive Tool
• jarsigner - JAR Signing and Verification Tool
• pack200 - JAR Packing tool
• unpack200 - JAR Unpacking tool
• extcheck - A utility to detect jar conflicts
• serialver - The Serial Version Command
• xjc - Java(TM) Architecture for XML Binding
• rmic - The Java RMI Compiler
• rmid - The Java RMI Activation System Daemon
• orbd - The Object Request Broker Daemon
• idlj - The IDL-to-Java Compiler
• servertool - The Java(TM) IDL Server Tool
• javaws - Java Web Start launcher command
• policytool - PolicyTool Administration GUI Utility
15.3
Hello World
Let’s see some examples from Wikipedia page about Java:
Stand-alone application
This is a minimal usage of Java, but it does not demonstrate object-oriented
programming well. No object is explicitly created since the keyword new is
never used.
// Hello.java
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
120 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
15.4
An example that better demonstrates object-oriented programming
// OddEven.java
import javax.swing.JOptionPane;
public class OddEven {
private int input;
public OddEven() {
input = Integer.parseInt(
JOptionPane.showInputDialog(
"Please Enter A Number"));
}
public void calculate() {
if (input % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
}
public static void main(String[] args) {
OddEven number = new OddEven();
number.calculate();
}
}
15.5
Applet
Applets are small programs designed to work embedded in a web browser.
This is a Hello World Applet:
// Hello.java
import java.applet.Applet;
import java.awt.Graphics;
public class Hello extends Applet {
public void paint(Graphics gc) {
gc.drawString("Hello, world!", 65, 95);
}
}
Web Page to call Hello Worl Applet:
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
121 of 171
<!-- Hello.html -->
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="Hello" width="200" height="200">
</applet>
</body>
</html>
15.6
Swing Application
There are three posibilities to make GUI Interfaces:
• AWT: Abstract Windowing Toolkit (Sun)
• Swing (Sun)
• SWT: Standard Widget Toolkit (IBM)
This is an example of Swing API:
// Hello.java (Java SE 5)
import java.awt.BorderLayout;
import javax.swing.*;
public class Hello extends JFrame {
public Hello() {
super("hello");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(new JLabel("Hello, world!"));
pack();
}
public static void main(String[] args) {
new Hello().setVisible(true);
}
}
122 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 16
Object Request Brokers
16.1
TAO
16.1.1
Documents about TAO
We have a guide in two volumes of TAO called: “TAO Developer’s Guide.
Building a standard in performance. Version 1.4a”. This guide has been made
by Object Computing, Inc.(OCI).
This is a list of the content of this guides:
1. Introduction
2. Building ACE and TAO
3. Getting Started
4. The Makefile, Project, and Workspace Creator (MPC)
5. TAO IDL Compiler
6. Error Handling
7. CORBA Messaging
8. Asynchronous Method Handling
9. Real-Time CORBA
10. Portable Interceptors
11. Value Types
12. Smart Proxies
13. Local Interfaces
14. IOR Table
15. Using Pluggable Protocols
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
123 of 171
16. Developing Pluggable Protocols
17. Multithreading with TAO
18. Configuring TAO Clients and Servers
19. ORB Initialization Options
20. Resource Factory
21. Server Strategy Factory
22. Client Strategy Factory
23. TAO Services Overview
24. Naming Service
25. Event Service
26. Real-Time Event Service
27. Notification Service
28. Interface Repository
29. TAO Security
30. Implementation Repository
31. Data Distribution Service
32. CIAO and CCM
I. Configuring ACE/TAO Builds
II. Choosing How To Build ACE and TAO
III. Building ACE and TAO on UNIX
IV. Building ACE and TAO Using Visual C++
V. Building ACE and TAO with Borland C++
VI. Using ACE and TAO with VwWorks
VII. Using ACE and TAO with LynxOS
VIII. Testing ACE and TAO on VxWorks and LynxOS
IX. CORBA Compliance
X. TAO and ACE Contributors
124 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
16.1.2
Building ACE and TAO
1. Untar file with source code of ACE & TAO:
export PATH_TO_ACE_TAO=‘pwd‘
tar xjf ACE-5.4.6+TAO-1.4.6.tar.bz2
2. Create symbolic links to configure TAO for our machine, in this example Linux:
cd
ln
cd
ln
cd
ACE_wrappers/ace
-s config-linux.h config.h
../include/makeinclude
-s platform_linux.GNU platform_macros.GNU
../..
3. Create some environment variables:
export ACE_ROOT=$PATH_TO_ACE_TAO/ACE_wrappers
export TAO_ROOT="$ACE_ROOT/TAO"
export LD_LIBRARY_PATH=$ACE_ROOT/ace:$ACE_ROOT/lib: \
$LD_LIBRARY_PATH
4. We generate the Makefiles, excluding some directories to speed up the
compilation time, so later we can compile:
bin/mwc.pl -type gnuace -recurse \
-exclude examples,performance-tests,tests,TAO/examples, \
TAO/interop-tests,TAO/performance-tests,TAO/tests, \
TAO/orbsvcs/tests,TAO/orbsvcs/examples, \
TAO/orbsvcs/tests,TAO/orbsvcs/performance-tests
5. Compile ACE & TAO using more than one thread in paralell if our processor supports it:
make -j3
16.2
MICO
MICO currently includes very limited documentation.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
125 of 171
16.3
eORB
16.4
OpenORB
16.5
ICa and ICa ORB
ICa (Integrated Control Architecture) is a distributed application developing framework. ICaORB is an object request broker, which follows the OMG
CORBA specifications. ICa and ICaORB have been developed by SCILabs
Ingenieros (www.scilabs.es)
In this document we will describe how to install the ICa files and how to
configure the system to use ICa. The machine and OS characteristics and
requirements are the following:
O.S.
Machine
Software
16.5.1
Linux Kernel 2.4.x or 2.6.x
PC, i586/i686 (or compatible)
gcc 3.2 or later, make 3.79 or later, gperf 3.0.1 or later
Preparing files
We must have the tarball distribution of ICa, named ICaLib xxx yyy zzz.tar.gz,
where:
• xxx is the operating system for which the library was developed for. In
our case, Linux.
• yyy is the architecture for which the library was developed for. In our
case, i586.
• zzz is the library version.
In this document we will use the distribution named:
ICaLib Linux i386 ppc 2003-07-09.tar.gz
This tar contains all libraries, sources and binaries needed to run ICa.
We should extract the tarball into the root directory (/). Doing this, ICa directory and files will be placed into the /usr/local/ directory. The directory
tree should appear as follows:
• /usr/local/ICa (Main Ica directory)
• /usr/local/ICa/bin/Linux/i386/idl (ICa IDL compiler)
• /usr/local/ICa/bin/Linux/i386/icans (ICa server)
• /usr/local/ICa/Configure (Script for environment config)
126 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
• /usr/local/ICa/include (ICa C++ header files)
• /usr/local/ICa/lib/Linux/i386/libICa-1.0.1.a (ICa library
for Linux/C++)
• /usr/local/Ica/scripts/ADL (ADL processing script)
16.5.2
Editing system files
In the ASlab we will run the ICa server in the machine C3P0, with IP number
138.100.76.202. This machine must be identified as “ICaHost”. Follow these
steps:
1. In /etc/hosts add the following line:
138.100.76.240 c3p0.disam.etsii.upm.es ICaHost
2. In /etc/services add these lines for ICa sockets:
ICa 2001/tcp
ICa 2001/udp
Using port 2001 is optional. You can use another free port of the service
list.
3. Write the following file and save it as /etc/init.d/ICa. Give execution permissions to this file.
service ICa
{
flags
socket_type
wait
user
server
log_on_failure
disable
}
= REUSE
= stream
= no
= root
= /usr/local/ICa/bin/Linux/i386/icans
+= USERID
= yes
4. Disable any proxy services, if there is anyone running in the system.
16.5.3
Environment variables
It’s highly recommended to add some environment variables initialization
into the /etc/profile script. This script is executed when any user logs
into the system. Add the following lines to the file mentioned above:
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
127 of 171
export
export
export
export
export
source
128 of 171
MCTYPES="i486 sun4u sun4m sun4c alpha"
MACHINE=$(uname -m)
OSTYPES="Linux SunOS OSF1"
SYSTEM=$(uname -s)
ICA=/usr/local/ICa
$ICA/Configure
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 17
Micro CCM
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
129 of 171
Part IV
ASL AB P LATFORMS
Chapter 18
ASLab’s Host Platforms
132 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Chapter 19
ASLab’s Target Platforms
This chapter describes the relevant issues of ASLab target platforms for ASLab
developers.
19.1
PCT Platforms
19.2
RCT Platforms
19.2.1
Higgs
CORBA, CIAO
Onboard Systems
Vaio Programming Language ?? Operating System: Fedora 9 Libraries
Offboard Systems
Sagan Programming Language ?? Operating System: OpenSuse 10 ?? Libraries
19.2.2
Khepera
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
133 of 171
Part V
A PPENDIXES
Appendix A
KDevelop
Keywords: KDevelop, programming, IDE
A.1
¿Qué es KDevelop?
KDevelop es un Entorno Integrado de Desarrollo (IDE) para Linux, muy similar a Microsoft Visual C++ para Windows. Integra todas las herramientas
necesarias para programar: el programa make, una consola, un editor, etc.
El desarrollo de programas con KDevelop es mucho más cómodo en todos los
sentidos: gestión de archivos, compilación, creación de interfaces gráficas de
usuario, etc. También proporciona una serie de plantillas para crear programas rápidamente: programas para consola o con interfaces gráficas (usando
QT o GTK, dos toolkits para desarrollo de interfaces gráficas).
La distribución Red Hat Linux 9 (Shrike) incluye el KDevelop 2.1, aunque ya
está disponible una beta de la versión 3.0, más depurada. Para saber más sobre KDevelop, es recomendable visitar la página web www.kdevelop.org.
A.2
Arrancando KDevelop por primera vez
La primera vez que un usuario concreto arranca el programa, se visualiza el
asistente para la configuración de KDevelop. En la inmensa mayorı́a de los
casos la configuración es muy simple. La pantalla de inicio del asistente se
muestra en la figura A.1
Pulsando ”Siguiente” vamos a la siguiente pantalla (figura A.2), donde debemos especificar el estilo para el entorno integrado de desarrollo. Es recomendable seleccionar ”Estilo de KDevelop 2.0”.
En la siguiente pantalla (figura A.3) elegimos el modo de la interfaz de usuario.
En mi opinión la más cómoda es la ”Vista con pestañas”
A continuación (figura A.4) el asistente nos muestra las herramientas del sistema que ha encontrado. Sólo debemos pulsar ”Siguiente”.
136 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Figure A.1: pantalla de inicio del asistente.
Figure A.2: selección del estilo.
Figure A.3: selección del modo de interfaz.
La siguiente pantalla (figura A.5) informa sobre la documentación de QT que
KDevelop ha encontrado en el sistema. Como antes, pulsamos ”Siguiente”.
En sistemas que no han sido especialmente configurados, el asistente no encontrará las librerı́as de documentación para KDE (figura A.6), pero normal-
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
137 of 171
Figure A.4: herramientas del sistema.
Figure A.5: documentación de QT.
mente no es un problema. Pulsamos ”Siguiente”.
Figure A.6: KDE library.
El siguiente paso (figura A.7) consiste en la indexación de la documentación.
Se hace de forma automática y no hay que indicar nada, pulsamos ”Siguiente”.
138 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Figure A.7: indexación de la documentación.
Figure A.8: pantalla final del asistente.
Con esto hemos terminado la configuración de KDevelop. Pulsando ”Finalizar” en la última pantalla (figura A.8) se cierra el asistente. Una vez cerrado el asistente se arrancará el programa. El asistente no volverá a mostrarse,
aunque si queremos volver a ejecutarlo, aparece un lanzador para ello en el
menú del sistema.
Estos pasos crean un entorno cómodo y de sobra suficiente para aprender a
programar con KDevelop. Si se desea se pueden elegir otros estilos en las
dos primeras pantallas, pero no conviene cambiar nada en las siguientes, que
corresponden a la configuración de la documentación, herramientas, etc.
A.3
Los proyectos
En KDevelop, cada programa tiene un ”proyecto” asociado, al igual que en
Visual C++. El concepto de proyecto es idéntico: agrupa todos los archivos
relacionados con el programa en un árbol de directorios y permite editarlos
y compilarlos de forma cómoda.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
139 of 171
KDevelop facilita diferentes plantillas de proyecto para crear programas (con
o sin interfaz gráfica) de forma rápida. De todos modos, cuando se empieza es recomendable usar un ”proyecto personalizado”. Cuando se crea
un proyecto personalizado, KDevelop no incluye plantillas ni genera ningún
tipo de código o Makefile de forma automática. De esta forma, el usuario
puede aprender desde cero muchos conceptos importantes, que se perderı́a
si empezase utilizando plantillas.
USando proyectos personalizados, el usuario debe crear su propio Makefile
e ir escribiendo y añadiendo los archivos de código.
A.4
El primer programa en KDevelop
En esta sección veremos cómo crear un proyecto personalizado para escribir
el programa ”Hola mundo”, compilarlo y ejecutarlo. Veremos los pasos básicos
para la creación de proyectos y la configuración de KDevelop para utilizarlos.
Emplearemos el mismo Makefile que describimos en el capı́tulo anterior.
Creación de un proyecto nuevo Para crear el proyecto, arrancamos KDevelop, y aparecerá en pantalla el IDE vacı́o (figura A.9). En el menú ”Proyecto”,
elegiremos la opción ”Nuevo...” (figura A.10), y aparecerá el cuadro de diálogo
del Asistente de Aplicaciones (figura A.11).
Figure A.9: IDE recién arrancado, sin proyecto.
Elección del tipo de proyecto En este ejemplo usaremos un proyecto personalizado, como dijimos. Para ello seleccionaremos, en la lista que aparece en la
ventana del asistente (figura A.11) la última opción: ”Otros/Personalizado” y
pulsaremos ”Siguiente”.
Datos del proyecto En la siguiente pantalla (figura A.12) debemos introducir
el nombre del proyecto, el directorio donde se almacenará, y algunos datos
del autor. Conviene seleccionar el directorio de destino antes de dar un nom-
140 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Figure A.10: menú proyecto.
Figure A.11: pantalla del asistente de aplicaciones.
bre al proyecto, porque el asistente crea automáticamente un directorio con
el nombre del proyecto, dentro del directorio indicado.
En esta misma pantalla, desactivamos todas las opciones (Linux Software
Map, Ficheros GNU estándar, etc.).
Control de versiones
La siguiente pantalla es para la configuración del control de versiones (CVS).
No explicaremos cómo usar CVS en este documento, ası́ que dejaremos desactivada esta opción (figura A.13).
Cabeceras de los archivos
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
141 of 171
Figure A.12: datos del proyecto.
Figure A.13: control de versiones.
En las dos siguientes pantallas el asistente nos pregunta si deseamos incluir
cabeceras en forma de comentario en los archivos de código fuente (tanto
142 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
en los archivos de cabecera como en los archivos .cpp). Por el momento
tampoco usaremos esta opción, ası́ que la desactivamos (figura A.14).
Figure A.14: cabeceras de archivos.
Por último nos aparece la pantalla de generación del proyecto. Pulsando el
botón ”Crear”, KDevelop genera los archivos y directorios necesarios, y va
mostrando mensajes informativos en la zona blanca de la ventana. Cuando
termina, visualiza el mensaje ”READY”; en este momento pulsamos ”Salir”,
y ya tenemos el proyecto dispuesto para trabajar (figura A.15).
Podemos ver en la zona izquierda del entorno de desarrollo ha aparecido
un árbol de directorios y algunos archivos (figura A.16). Este es el árbol de
nuestro proyecto, donde aparecerán los archivos de código que vayamos creando.
Estructura del árbol de directorios Yo uso un árbol de directorios personalizado, que resulta muy útil a la hora de colocar los archivos de código. Partiendo del directorio padre del proyecto (raı́z del árbol mostrado en el IDE),
creo los siguientes subdirectorios:
bin: en este directorio almaceno el binario de mi programa (TARGET).
lib: aquı́ guardo las librerı́as especiales (no propias del sistema) que utiliza
mi programa.
obj: en este directorio se generan todos los archivos objeto (.o), para que no
se mezclen con los archivos de código al compilar.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
143 of 171
Figure A.15: pantalla de generación.
Figure A.16: árbol de directorios del proyecto.
Pueden crearse tantos subdirectorios como se desee, pero hay que tenerlos en
cuenta a la hora de crear el Makefile, como veremos (usaremos variables
para almacenar los nombres de estos subdirectorios).
Crear un fichero de código A partir de ahora todo es crear ficheros de código
fuente, añadir un Makefile, y compilar. Para crear archivos de código, seleccionamos en el menú ”Archivo”, la opción ”Nuevo”, como se muestra en
la figura A.17
Aparece entonces un cuadro de diálogo (figura A.18) donde se nos pregunta
qué tipo de archivo queremos crear (.cpp, .o, .txt, etc.), su nombre y
dónde (en qué subdirectorio) queremos colocarlo. Yo suelo colocar los archivos
de código ”generales” en el directorio padre del proyecto.
Una vez cerrado este cuadro de diálogo podemos empezar a escribir el código
en la zona superior derecha del entorno de desarrollo. Notar que habrá apare-
144 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Figure A.17: crear un archivo nuevo.
Figure A.18: datos del nuevo archivo.
cido el archivo creado en el árbol del proyecto, a la izquierda; haciendo doble
click sobre él, abriremos el archivo para editarlo cuando sea necesario. Podemos tener varios archivos abiertos a la vez; en ese caso aparecerán pestañas
en la zona superior del área de edición, con los nombres de cada uno de los
archivos abiertos.
Para seguir con nuestro ejemplo, crearemos un archivo llamado main.cpp, y
escribiremos en él el código del ”Hola Mundo” que describimos al principio
del documento. Sólo queda definir el Makefile para que KDevelop pueda
compilar el programa.
Crear el Makefile Para crear el Makefile haremos lo mismo que para un
archivo de código fuente, pero especificando que será un archivo de texto
(sin extensión). Llamaremos al archivo ”Makefile” y lo guardaremos en el
directorio principal del proyecto (figura A.19).
Como siempre, aparecerá el nuevo archivo en la zona de edición y en el árbol
de directorios del proyecto. Para escribir el contenido podemos usar el código
presentado al final de la sección 1.4.2, con algunas modificaciones. Como no
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
145 of 171
Figure A.19: crear el Makefile.
vamos a usar librerı́as, quitaremos las lı́neas correspondientes:
# Variables principales -------------------TARGET = bin/cosa
# Herramientas ----------------------------CC = gcc
CPP = g++
LD = g++
MAKE = make
# Flags -----------------------------------CFLAGS = -O2 -w
# Archivos --------------------------------SOURCES = $(wildcard *.cpp)
OBJS = $(patsubst obj/%.o, %.cpp, $(wildcard *.cpp))
# Regla principal -------------------------ifeq (obj/.depend,$(wildcard obj/.depend))
$(TARGET) : $(OBJS)
include obj/.depend
endif
# Reglas secundarias ----------------------obj/%.o :
146 of 171
%.cpp
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
$(CPP) $(CPPFLAGS) -o $@ -c $<
% :
$(LD) $(CPPLAGS) $(LDFLAGS) -o $@ $ˆ $(LIBS)
dep :
$(CC) -M $(CFLAGS) $(SOURCES) > obj/.depend
# Reglas adicionales ----------------------clean:
rm -f obj/*.o
rm -f $(TARGET)
rm -f obj/.depend
all:
$(MAKE) clean
$(MAKE)
# -----------------------------------------Hay que notar que es necesario crear los directorios bin y obj dentro del
árbol de directorios del proyecto antes de compilar, y que se modifican levemente las lı́neas del Makefile para usar estos directorios.
Hemos eliminado las variables relacionadas con las librerı́as, ya que no vamos a usar ninguna, y colocaremos además el archivo de dependencias en el
subdirectorio obj.
Para que KDevelop encuentre el Makefile debemos indicarle en qué directorio debe ejecutar make. Para ello, pulsamos la el elemento ”Opciones” en
el menú ”Proyecto” (figura A.20)
En el cuadro de diálogo que aparece, seleccionamos ”Opciones de Make”,
y pulsamos el botón con el directorio en la zona inferior izquiera, como se
muestra en la figura A.21:
Nos aparecerá un cuadro de diálogo en el que debemos seleccionar el directorio principal del proyecto, donde hemos guardado el Makefile. Al aceptar y
al cerrar el cuadro de diálogo de opciones nos preguntará si queremos usar la
ruta relativa al directorio, o la ruta absoluta. En ambos casos elegimos ”Ruta
absoluta” (figura A.22).
Con esto KDevelop queda listo para compilar.
Compilación Para dar la orden de compilación pulsamos la tecla de función
F8. En la zona inferior del entorno, en la pestaña ”Mensajes”, irán apareciendo mensajes acerca de las operaciones que va haciendo el programa make
y su resultado (figura A.23). Los mensajes en azul son informativos, y los rojos
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
147 of 171
Figure A.20: opciones de proyecto.
Figure A.21: opciones de make.
Figure A.22: ruta al Makefile.
son avisos o warnings. Si todo sale bien, aparecerá el mensaje ”**conseguido**”
(figura A.24).
Después de la compilación podemos dar al elemento ”Actualizar” del menu
148 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Figure A.23: compilación.
Figure A.24: mensajes de compilación.
”Ver” (figura A.25), para que se actualice el árbol de directorios del proyecto
y muestre los archivos generados, incluyendo el archivo ejecutable.
Figure A.25: menú ver.
Podemos ejecutar el programa haciendo doble click sobre su nombre en el
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
149 of 171
árbol de directorios, o desde la pestaña de consola en la parte inferior derecha
del entorno de desarrollo (figura A.26).
Figure A.26: consola del entorno de desarrollo.
150 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Appendix B
Rational Software Architect
B.1
Notes about Rational Software Architect 6.0 in Linux
Rational Software Architect 6.0 is certified for use in only two distributions:
• RedHat Enterprise Linux WS 3.0
• SuSE Linux Enterprise Server 9.0
I use Rational Software Architect 6.0 with:
• Fedora Core 6.0
• Mandriva 2006
And I have made the following change to the system in order to use the Welcome screen and the Help of the Rational:
• Install the Flash Plugin of Macromedia, now Adobe, version 6.0r69 or
higher. Last version is 7.0r68 (28/11/2006).
• Install Mozilla Browser 1.4-1.6x. Later versions don’t work correctly
with Rational, because some text is missing en the Welcome & Help
screens. The file /etc/gre.conf must point to the path where this browser
is installed. This is a list of the file /etc/gre.conf I am using:
[1.6]
GRE_PATH=/usr/lib/mozilla-1.6
• You also need GTK version 2.2.1 or later.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
151 of 171
Figure B.1: Screen capture of the Rational Welcome Screen.
Figure B.2: Screen capture of the Rational Welcome Screen, General Sight.
152 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Figure B.3: Screen capture of the Rational Welcome Screen, Analysis and Design of Applications, Introduction to Modelling.
B.2
Notes about Rational Software Architect 7.0 in Linux
Rational Software Architect 7.0 is certified for use in only four distributions:
• Red Hat Enterprise Linux WS 4.0
• Red Hat Desktop 4.0
• SUSE LINUX Enterprise Server 9
• Novel LINUX Desktop 9
And you can install the following items in order to use the Welcome screen
and the Help of the Rational:
• Install the Flash Plugin of Macromedia, now Adobe. Last version is
9.0r31 (06/03/2007).
• Install Firefox Browser. The file /etc/gre.d/gre.conf must point to the
path where this browser is installed. This is a list of the file /etc/gre.d/gre.conf
I am using:
[1.5.0.10]
GRE_PATH=/usr/lib/firefox-1.5.0.10
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
153 of 171
Figure B.4: Screen capture of the Rational 7.0 Welcome Screen.
Figure B.5: Screen capture of the Rational Help Screen, General Sight.
154 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
There is a bug in RSD 7.0.0, UML modeling in Linux gives invisible objects,
objects only visible in outline window. The problem is the anti-aliasing feature of the modeling tool. Go to “Window → Preferences → Modeling →
Diagrams” and disable “anti-aliasing”. Now the models should display correctly.
Figure B.6: Screen capture of a Rational 7.0 UML Diagram.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
155 of 171
Appendix C
Using RSA and CVS
This appendix explains how to set up and work in a team environment with
Rational Software Architect by importing an existing project and practicing
model-driven, team-oriented development. The scenario in this article specifically involves two roles: configuration manager and developer. The user ID
for the configuration manager is cvs admin. The two developers have the
user IDs dev1 and dev2.
C.1
Before you begin: Installing and configuring software
You must perform key software installation and configuration tasks before
you set up your environment.
C.1.1
Prerequisites
The following software must be installed on client workstations:
• Rational Software Architect 6.0
• Concurrent Versions System 3.0.1
C.1.2
CVS repository assumptions
This scenario assumes that your Concurrent Versions System (CVS) repository is created and configured for all three users.
C.1.3
Configuring RSA/eclipse workspace
We use ISO-8859-1 encoding. To configure the workspace with that encoding:
Window → Preferences → General → Workspace → Text file encoding →
Other: ISO-8859-1
156 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
C.2
Sharing a modeling project
You share a modeling project, so that other team members can also work on
it. In this section, you start Rational Software Architect as cvs admin, import
a modeling project, and share it in CVS.
C.2.1
Starting Rational Software Architect
Start Rational Software Architect and create an initial workspace.
To start Rational Software Architect:
1. Click Start > Programs > IBM Rational > IBM Rational Software Architect V6.0 > Rational Software Architect.
2. In the Workspace Launcher window, in the Workspace field, specify a
workspace and click OK.
Note: Your CVS repository location and your Rational Software Architect
workspace should always be separate.
C.2.2
Importing an existing modeling project
In this exercise, you import an existing modeling project called Piggy Bank.
In accordance with the Rational Unified Process (RUP), the Piggy Bank sample UML model is divided into three models that each describe a different
aspect of the system: the use-case model, analysis model, and design model.
To import the Piggy Bank modeling project:
1. Click Help > Samples Gallery.
2. In the Contents pane, navigate to Application samples > Piggy Bank
Application > Piggy Bank Models.
3. In the right pane, click Import the sample.
4. In the Sample Banking Models wizard, on the Piggy Bank Models page,
accept the default project name and click Finish.
5. Close the Samples Gallery.
The following figure illustrates how the Piggy Bank modeling project is displayed in the Model Explorer view.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
157 of 171
Figure C.1: Piggy Bank modeling project.
C.2.3
Sharing a project
It is possible to share a RSA project to allow other team members to access it.
To share your project:
1. In the Model Explorer view, right-click Piggy Bank Models; then click
Team > Share Project.
2. In the Share Project wizard, on the Share Project page, click CVS and
click Next.
3. On the Share Project with CVS Repository page, click a repository location and click Next.
4. On the Enter Module Name page, click Use project name as module
name and click Next.
5. On the Share Project Resources page, click Commit All Changes.
6. In the Add to CVS Version Control window, click Yes.
7. In the Commit window, type Share project and click OK.
8. On the Share Project Resources page, click Finish.
C.2.4
Adding to the modeling project
Make changes to your models and store them in CVS, so that other team
members can view them. Update a use-case diagram with an action.
To update a use-case diagram:
1. In the Model Explorer view, double-click Use Case Model.emx.
158 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Figure C.2: Opening the Display Balance Activity Diagram.
2. Navigate to Use Case Model > Account Operations > Display Balance > Display Balance and double-click Display Balance Activity Diagram.
3. In the Palette, click Action.
4. In the diagram editor, click above Display Accounts with balance.
5. In the diagram editor, rename Action to Select Account.
6. In the Palette, click Control Flow.
7. In the diagram editor, click Select Account and drag the cursor to Display Accounts with balance.
8. In the guard condition, type [true].
9. Click the end of the guard condition that points to Display Accounts
with balance and drag the cursor to Select Account.
The following figure illustrates how a new action is displayed in the
diagram editor.
10. To save your changes, click File > Save All.
C.2.5
Committing your work to the repository
Commit your changes to the repository, so that other users can view them.
To commit your work to the repository:
1. In the Model Explorer view, right-click Piggy Bank Models; then click
Team > Synchronize with Repository.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
159 of 171
Figure C.3: Creating an action.
2. In the Synchronize view, in Outgoing Mode, right-click Use Case Model.emx;
then click Commit.
3. In the Commit Comment window, type Create Action and click OK.
C.2.6
Developing models as part of a team
At this point in the scenario, the administrator has finished setting up the
development environment. In this exercise, the focus switches to the development process and to two developers with the user IDs dev1 and dev2.
C.2.7
Setting up work areas for the developers
In this exercise, you set up the individual work areas for dev1 and dev2. This
exercise assumes that the CVS repository is already created and configured
for dev1 and dev2.
1. Log in as dev1.
2. Click Start > Programs > Rational Software > Rational Software Architect.
3. In the CVS Repository Exploring perspective, expand HEAD.
4. Right-click Piggy Bank Models; then click Check Out As.
5. To load Piggy Bank models into your workspace, in the Check Out As
window, click Finish.
6. To set up another work area for dev2, repeat steps 1 through 5.
160 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
C.2.8
Adding to the modeling project
As dev2, make a change to a use-case diagram by renaming an action.
To rename an action:
1. In the Model Explorer view, double-click Use Case Model.emx.
2. Navigate to Use Case Model > Account Operations > Display Balance > Display Balance and double-click Display Balance Activity Diagram.
3. In the diagram editor, rename Display Accounts with balance to Display Selected Account.
4. Click File > Save All.
The following figure illustrates how a renamed action is displayed in the diagram editor.
Figure C.4: Renaming an action.
C.2.9
Committing your work to the repository
Commit your changes to the repository, so that other users can view them.
To commit your work to the repository:
1. In the Model Explorer view, right-click Piggy Bank Models; then click
Team > Synchronize with Repository.
2. In the Synchronize view, in Outgoing Mode, right-click Use Case Model.emx;
then click Commit.
3. In the Commit Comment window, type Rename Action and click OK.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
161 of 171
C.2.10
Updating the work area for dev1
Update the work area for dev1 with the latest changes that dev2 committed
to the repository.
To update the work area for dev1:
1. Log in as dev1.
2. Click Start > Programs > Rational Software > Rational Software Architect.
3. In the Model Explorer view, right-click Piggy Bank Model; then click
Team > Synchronize with Repository.
4. In the Synchronize view, in Incoming Mode, right-click Piggy Bank
Model; then click Update.
C.2.11
Starting parallel development: Comparing and merging models
In this exercise, you perform parallel development. The two users on your
team make different changes to the same model element. In the next exercise, the second user tries to synchronize with the repository, and then must
perform a merge to resolve the differences.
A merge typically starts when you check in a model to a configuration management system and a newer version of the same model already exists in the
repository. At the start of the merge, all non-conflicting differences and trivial conflicts are resolved automatically. You must then manually resolve the
remaining conflicts by selecting a version of a model from which to accept
changes. After you resolve the remaining conflicts, you can save the merged
model and close the merge editor.
Introducing conflicts to the model
In this exercise, dev1 introduces a change to a file, then commits the file.
When dev2 makes a conflicting change to the same file, dev2 must merge the
two files before committing changes to the repository.
To create a conflicting change:
1. As dev1, in the Model Explorer view, double-click Use Case Model.emx.
2. Navigate to Use Case Model > Account Operations and double-click
Account Operations Use Cases.
3. In the diagram editor, rename Teller to Auditor.
4. Click File > Save All.
162 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
5. Commit your changes to the repository:
(a) In the Model Explorer view, right-click Piggy Bank Models; then
click Team > Synchronize with Repository.
(b) In the Synchronize view, click Outgoing Mode.
(c) Right-click Use Case Model.emx; then click Commit.
(d) In the Commit Comment window, type dev1 changes and click
OK.
6. To exit Rational Software Architect, click File > Exit.
7. Log in as dev2.
8. In the Model Explorer view, double-click Use Case Model.emx.
9. Navigate to Use Case Model > Account Operations and double-click
Account Operations Use Cases.
10. In the diagram editor, rename Teller to Manager.
11. Click File > Save All.
Resolving the conflict
At this point, dev1 and dev2 have both made changes to the same file. The
dev1 user has committed changes. The dev2 user has not yet committed
changes. When dev2 synchronizes with the repository, a merge initiates and
dev2 must resolve any conflicts that exist before committing changes to the
repository.
To resolve the conflict:
1. As dev2, in the Model Explorer view, right-click Use Case Model.emx;
then click Team Synchronize with Repository.
2. In the Synchronize view, in Incoming Mode, double-click Use Case
Model.emx (which is identified by a conflict icon).
3. Click Synchronize.
The Merge window opens. You can view the differences and conflicts
between contributor and ancestor files in the Left, Right, and Ancestor
views. You can also view details about each difference and conflict in
the Structural Differences view. The Merged result view displays the
merged model.
4. To accept the change that dev2 made, in the Merge window, in the
Structural Differences view, right-click Conflicting changes; then click
Resolve with Left Contributor.
5. In the Merged result view, click Save as Left contributor.
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
163 of 171
Figure C.5: Resolving a conflict.
Figure C.6: Saving a merged model.
164 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
6. Close the Merge window.
7. In the Synchronize view, in Incoming Mode, right-click Use Case Model.emx;
then click Mark as Merged.
8. Click Outgoing Mode.
9. Right-click Use Case Model.emx; then click Commit.
10. In the Commit Comment window, type merged use-case model and
click OK.
The merge is now complete and the results are under CVS control.
C.3
Resources
C.3.1
Learn
http://www-128.ibm.com/developerworks/rational/library/05/0830 Custic/index.html
Scenarios of working in a team development environment: Using IBM Rational Software Architect and base ClearCase: This first scenario describes
how to work in a team development environment using Rational Software
Architect and base ClearCase.
http://www-128.ibm.com/developerworks/rational/library/05/0920 scenarios/index.html
Scenarios of working in a team development environment: Using IBM Rational Software Architect and UCM: This second scenario describes how to
work in a team development environment using Rational Software Architect
and UCM.
http://www-128.ibm.com/developerworks/rational/library/05/802 comp3/
Comparing and merging UML models in IBM Rational Software Architect:
Part 3: This article is part of a series of articles that discuss how to compare
and merge UML models in Rational Software Architect.
http://www-128.ibm.com/developerworks/rational/library/05/kunal/
Introducing IBM Rational Software Architect: Improved usability makes software development easier: This article is a basic introduction to the Rational
Software Architect product.
http://www-128.ibm.com/developerworks/rational/products/rsa/
IBM Rational Software Architect product page: Find technical documentation, how-to articles, education, downloads, and product information about
Rational Software Architect.
http://www-130.ibm.com/developerworks/rational/products/clearcase/
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
165 of 171
IBM Rational ClearCase product page: Find technical documentation, how-to
articles, education, downloads, and product information about ClearCase.
C.3.2
Get products and technologies
http://www14.software.ibm.com/webapp/download/brand.jsp?b=Rational
IBM Rational Software Architect: Download a trial version from developerWorks.
Discuss
http://www-128.ibm.com/developerworks/forums/dw forum.jsp?forum=430&cat=24
Participate in the discussion forum.
http://www.ibm.com/developerworks/forums/dw rforums.jsp
Rational Software Architect, Software Modeler, Application Developer and
Web Developer forum: Ask questions about Rational Software Architect.
http://www.ibm.com/developerworks/blogs/
developerWorks blogs: Participate in the developerWorks community.
166 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Appendix D
Target Platforms
This appendix provides a list of the target processors supported by some useful compilers and libraries available in ASLab.
D.1
Targets supported by GCC
GCC target processors as of version 4.1 include:
Alpha
ARM
Atmel AVR
Blackfin
HC12
H8/300
IA-32 (x86)
x86-64
IA-64
MorphoSys
Motorola 68000
MIPS
PA-RISC
PDP-11
PowerPC
R8C/M16C/M32C
System/390/zSeries
SuperH
SPARC
VAX
Lesser-known target processors supported in the standard release have included:
A29K
68HC11
ARC
MCORE
C4x
MMIX
ETRAX CRIS
MN10200
D30V
MN10300
DSP16xx
Motorola 88000
FR-30
NS32K
FR-V
ROMP
Intel i960
Stormy16
IP2000
V850
M32R
Xtensa
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
167 of 171
Additional processors have been supported by GCC versions maintained
separately from the FSF version:
D10V
MicroBlaze
Nios II and Nios
PDP-10
MSP430
Z8000
The following hosts/targets have specific instalation notes:
alpha*-*-*
alpha*-dec-osf*
alphaev5-cray-unicosmk*
arc-*-elf
arm-*-elf arm-*-coff arm-*-aout
xscale-*-*
avr
Blackfin
c4x
DOS
*-*-freebsd*
h8300-hms
hppa*-hp-hpux*
hppa*-hp-hpux10
hppa*-hp-hpux11
*-*-linux-gnu
i?86-*-linux*aout
i?86-*-linux*
i?86-*-sco3.2v5*
i?86-*-solaris2.10
i?86-*-udk
ia64-*-linux
D.2
ia64-*-hpux*
*-ibm-aix*
iq2000-*-elf
m32c-*-elf
m32r-*-elf
m6811-elf
m6812-elf
m68k-*-*
m68k-hp-hpux
m68k-uclinux
mips-*-*
mips-sgi-irix5
mips-sgi-irix6
powerpc*-*-* powerpc-*sysv4
powerpc-*-darwin*
powerpc-*-elf powerpc*-sysv4
powerpc*-*-linux-gnu*
powerpc-*-netbsd*
powerpc-*-eabisim
powerpc-*-eabi
powerpcle-*-elf
powerpcle-*-sysv4
powerpcle-*-eabisim
powerpcle-*-eabi
s390-*-linux*
s390x-*-linux*
s390x-ibm-tpf*
*-*-solaris2*
sparc-sun-solaris2*
sparc-sun-solaris2.7
sparc-*-linux*
sparc64-*-solaris2*
sparcv9-*-solaris2*
*-*-sysv*
vax-dec-ultrix
*-*-vxworks*
x86 64-*-* amd64-*-*
xtensa-*-elf
xtensa-*-linux*
Microsoft Windows
OS/2
Older systems
all ELF targets (SVR4,
Solaris 2, etc.)
Standard C Library
D.2.1
Targets supported by GNU C Library
http://www.gnu.org/software/libc/
The GNU C Library currently supports configurations that match the following patterns:
168 of 171
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
alpha*-*-linux
arm-*-linux
cris-*-linux
hppa-*-linux
ix86-*-gnu
ix86-*-linux
ia64-*-linux
m68k-*-linux
mips*-*-linux
powerpc-*-linux
s390-*-linux
s390x-*-linux
sparc-*-linux
sparc64-*-linux
Former releases of this library (version 2.1 and/or 2.0) used to run on the following configurations:
arm-*linuxaout
arm-*none
Very early releases (version 1.09.1 and perhaps earlier versions) used to run
on the following configurations:
alpha-dec-osf1 alpha-*linuxecoff ix86-*-bsd4.3
ix86-*-isc2.2 ix86-*-isc3.n
ix86-*-sco3.2
ix86-*sco3.2v4 ix86-*-sysv
ix86-*-sysv4
ix86force cpu386-none
ix86-sequent-bsd
i960-nindy960-none
m68k-hp-bsd4.3 m68kmvme135-none m68kmvme136-none m68ksony-newsos3
m68k-sony-newsos4
m68k-sun-sunos4.n
mips-dec-ultrix4.n
mips-sgi-irix4.n sparcsun-solaris2.n sparc-sunsunos4.n
Like recent versions of the GNU C Library only support Linux, it is prefereable to use other smaller libraries for embedded systems like:
dietlibc
Newlib
UClibc
D.2.2
dietlibc
http://www.fefe.de/dietlibc/
The diet libc is a libc that is optimized for small size. It can be used to create
small statically linked binaries for Linux on
alpha
arm
hppa
ia64
i386
mips
D.2.3
s390
sparc
sparc64
ppc
x86 64
Newlib (requires MMU)
http://sourceware.org/newlib/
Newlib is a C library intended for use on embedded systems. It is a conglomeration of several library parts, all under free software licenses that make
ASLab.org / ASLab Development Manual / R-2006-005v 2.0 Draft
169 of 171
them easily usable on embedded products.
Newlib is only available in source form. It can be compiled for a wide array
of processors, and will usually work on any architecture with the addition of
a few low-level routines.
D.2.4
UClibc (MMU-less)
http://www.uclibc.org/about.html
uClibc (aka µClibc/pronounced yew-see-lib-see) is a C library for developing
embedded Linux systems. It is much smaller than the GNU C Library, but
nearly all applications supported by glibc also work perfectly with uClibc.
Porting applications from glibc to uClibc typically involves just recompiling
the source code.
uClibc even supports shared libraries and threading. It currently runs on
standard Linux and MMU-less (also known as µClinux) systems with support for the following processors:
cm i960
alpha
amd64
ARM
Blackfin
cris
h8300
hppa
i386
170 of 171
ia64
m68k
mips/mipsel
PowerPC
SH
SPARC
v850
R-2006-005 v 2.0 Draft / ASLab Development Manual / ASLab.org
Title: ASLab Development Manual
Subtitle: Processes and Toolchains
Author: Ricardo Sanz, Adolfo Hernando, Adolfo Yela, Carlos Hernández
Date: 17-04-2008
Reference: R-2006-005 v 2.0 Draft
URL: www.aslab.org
c 2006 ASLab
Autonomous Systems Laboratory
U NIVERSIDAD P OLIT ÉCNICA DE M ADRID
C /J OS É G UTI ÉRREZ A BASCAL , 2
M ADRID 28006 (S PAIN )
aslab.org

Documentos relacionados