Introduction To GCC
Introduction To GCC
by
J.DavidOrtegaPacheco
FirstVersion
2009
GCCreview
GCC:TheGNUCompilerCollection
TheoriginalauthoroftheGNUCCompiler
(GCC) is Richard Stallman, the founder of
theGNUProject.
The GNU project was started in 1984 to
create a complete Unixlike operating
systemasfreesoftware,inordertopromote
freedom and cooperation among computer
usersandprogrammers.
GCCreview
GCC:TheGNUCompilerCollection
GCCreview
GCC:TheGNUCompilerCollection
GCCreview
GCC:TheGNUCompilerCollection
This was a significant breakthrough, being the first
portable ANSI C optimizing compiler released as free
software.SincethattimeGCChasbecomeoneofthemost
importanttoolsinthedevelopmentoffreesoftware.
Isanintegrateddistributionofcompilersforseveralmajor
programminglanguages
C,C++,ObjectiveC,ObjectiveC++,Fortran,JavaandAda
GCCreview
GCC:TheGNUCompilerCollection
GCCreview
GCC:TheGNUCompilerCollection
MostofthecompilersforlanguagesotherthanChavetheir
ownnames:
Ccompiler(gcc)
C++compiler(g++)
Fortrancompiler(gfortran)
ObjectiveCcompiler(gobjc)
ObjectiveC++compiler(gobjc++)
Javacompiler(gcj)
Adacompiler(GNAT)
GCCreview
CompilingaCprogram
GCC
Sourcefile:hello.c
$gccWallhello.cohello
#include<stdio.h>
intmain(void)
{
printf("Hello,world!\n");
return0;
}
Wall:Warnings
o:Outputfile
$./hello
Hello,world!
GCCreview
Findingerrors
GCC
$gccbad.cobad
Sourcefile:bad.c
#include<stdio.h>
intmain(void)
{
printf("Twoplustwois%f\n",4);
return0;
}
./bad
Two
plus
two
is
0.047119
$ gcc Wall bad.c o
bad
Wall:Warningoption
bad.c:Infunctionmain:
bad.c:6: warning: format %f expects type
double,butargument2hastypeint
GCCreview
Findingerrors
GCCreview
Compilingmultiplesourcefiles
Aprogramcanbesplitupintomultiplefiles.Thismakes
iteasiertoeditandunderstand,especiallyinthecaseof
large programs. It also allows the individual parts to be
compiledindependently
Example
main.c
hello.c
hello_fn.c
hello.h
GCCreview
Compilingmultiplesourcefiles
Example
main.c
#include"hello.h"
intmain(void)
{
hello("world");
return0;
}
GCCreview
Compilingmultiplesourcefiles
Example
hello_fn.c
hello.h
#include<stdio.h>
#include"hello.h"
Declaration of the function voidhello(constchar*name)
{
hello
printf("Hello,%s!\n",name);
}
voidhello(constchar*name);
GCCreview
Compilingmultiplesourcefiles
Diferencebetween#include<FILE.h>and#include"FILE.h"
The former searches for FILE.h in the current directory
beforelookinginthesystemheaderfiledirectories.
#include <FILE.h> searches the system header files, but
doesnotlookinthecurrentdirectorybydefault.
GCCreview
Compilingmultiplesourcefiles
Compilingthesourcefiles
$gccWallmain.chello_fn.conewhello
The header file hello.h is not specified. The directive
#include"hello.h"inthesourcefilesinstructsthecompiler
toincludeitautomaticallyattheappropriatepoints.
$./newhello
Hello,world!
GCCreview
Compilingmultiplesourcefiles
Compilingsourcefilesindependently
Whenprogramsarestoredinindependentsourcefiles,only
the files which have changed need to be recompiled after
the source code has been modified. The source files are
compiled separately and then linked together a two stage
process:
Secondstage
Firststage
Afileiscompiledwithout
creating an executable.
The result is referred to
asanobjectfile
Theobjectfilesaremergedtogether
by a separate program called the
linker. The linker combines all the
object files together to create a
singleexecutable
GCCreview
Compilingmultiplesourcefiles
Compilingsourcefilesindependently
Firststage
$gccWallcmain.c
cisusedtocompileasourcefiletoanobjectfile
This produces the file main.o containing the machine code
forthemainfunction
$gccWallchello_fn.c
Thisproducestheobjectfilehello_fn.o
GCCreview
Compilingmultiplesourcefiles
Compilingsourcefilesindependently
Whencompilingwithcthecompilerautomaticallycreates
an object file whose name is the same as the source file,
with.oinsteadoftheoriginalextension.
There is no need to put the header file hello.h on the
command line, since it is automatically included by the
#includestatementsinmain.candhello_fn.c
GCCreview
Compilingmultiplesourcefiles
Compilingsourcefilesindependently
Secondstage
$gccmain.ohello_fn.oohello
ocreatetheexecutablefilehello
There is no need to use the Wall warning option
since the individual source files have already been
successfullycompiledtoobjectcode.
$./hello
Hello,world!
GCCreview
Linkorderforobjectfiles
GCCreview
Recompilingandrelinking
Ifweeditthemainprogrammain.candmodifyittoprint
agreetingtoeveryoneinsteadofworld
Theupdatedfilemain.ccannowberecompiled:
$gccWallcmain.c
Thisproducesanewobjectfilemain.o
GCCreview
Recompilingandrelinking
Thereisnoneedtocreateanewobjectfileforhello_fn.c,
sincethatfileandtherelatedfilesthatitdependson,such
asheaderfiles,havenotchanged
Thenewobjectfilecanberelinkedwiththehellofunction
tocreateanewexecutablefile:
$gccmain.ohello_fn.oohello
$./hello
Hello,everyone!
GCCreview
Recompilingandrelinking
GCCreview
Linkingwithexternallibraries
GCCreview
Recompilingandrelinking
GCCreview
Recompilingandrelinking
Incorrect
$gccWallcalc.cocalc
Example
Sorcefile:calc.c
#include<math.h>
#include<stdio.h>
intmain(void)
{
doublex=sqrt(2.0);
printf("Squarerootof2.0is%f\n",x);
return0;
}
GCCreview
Recompilingandrelinking
Example
Correct
Oneobviousbutcumbersomeway:
$gccWallcalc.c/usr/lib/libm.aocalc
$./calc
Thesquarerootof2.0is1.414214
Toavoidtheneedtospecifylongpaths,thecompilerprovides
ashortcutoptionlforlinkingagainstlibraries
$gccWallcalc.clmocalc
ThecompileroptionlNAMEwillattempttolinkobjectfiles
with a library file libNAME.a in the standard library
directories
GCCreview
Linkorderoflibraries
Theorderingoflibrariesonthecommandlinefollowsthe
same convection as for object files : they are searched
from left to right a library containing the definition of a
function should appear after any source files or object
fileswhichuseit.
$gccWallcalc.clmocalc(correct)
$ccWalllmcalc.cocalc(incorrect),becausethereisno
library or object file containing sqrt after calc.c. The
optionlmshouldappearafterthefilecalc.c
GCCreview
Linkorderoflibraries
Whenseverallibrariesarebeingused,thesameconvention
should be followed for the libraries themselves. A library
whichcallsanexternalfunctiondefinedinanotherlibrary
shouldappearbeforethelibrarycontainingthefunction.
$gccWalldata.clglpklm
The object files in libglpk.a use functions defined in
libm.a
GCCreview
Usinglibraryheaders
Sorcefile:calc.c
#include<stdio.h>
intmain(void)
{
doublex=sqrt(2.0);
printf("Squarerootof2.0is%f\n",x);
return0;
}
#inlcude<math.h>ismissing
Compiling the program without any warning options will
produceanexecutablefilewhichgivesincorrectresults
GCCreview
Usinglibraryheaders
ThiscanbedetectedbyturningonthewarningoptionWall
$gccWallbadpow.clm
GCCreview
CreatingalibrarywiththeGNUarchiver
TheGNUarchiverarcombinesacollectionofobjectfilesinto
asinglearchivefile,alsoknownasalibrary.
Example
hello_fn.c
bye_fn.c
#include<stdio.h>
#include"hello.h"
voidhello(constchar*name)
{
printf("Hello,%s!\n",name);
}
#include<stdio.h>
#include"hello.h"
voidbye(void)
{
printf("Goodbye!\n");
}
GCCreview
CreatingalibrarywiththeGNUarchiver
Example
hello.h
voidhello(constchar*name);
voidbye(void);
GCCreview
CreatingalibrarywiththeGNUarchiver
Example
Theseobjectfilescanbecombinedintoastaticlibrary:
$arcrlibhello.ahello_fn.obye_fn.o
cr stands for create and replace. If the library does not
exist, it is first created. If the library already exists, any
original files in it with the same names are replaced by the
new files specified on the command line. The first argument
libhello.a is the name of the library. The remaining
argumentsarethenamesofthe objectfilestobecopiedinto
thelibrary.
GCCreview
CreatingalibrarywiththeGNUarchiver
Example
main.c
#include"hello.h"
intmain(void)
{
hello("everyone");
bye();
return0;
}
Assumingthelibrarylibhello.aisstored
inthecurrentdirectory:
$gccWallmain.clibhello.aohello
$./hello
Hello,everyone!
Goodbye!
GCCreview
CreatingalibrarywiththeGNUarchiver
Example
The shortcut library linking option l can also be used to link
the program, without needing to specify the full filename of the
libraryexplicitly
$gccWallL.main.clhelloohello
The option L. is needed to add the current directory to the
librarysearchpath
GCCreview
Howthecompilerworks?
Compilationisamultistageprocessinvolvingseveraltools:
GNUCompileritself(gccfrontend)
GNUAssembleras
GNULinkerld.
Thecompletesetoftoolsusedinthecompilationprocessis
referredtoasatoolchain
GCCreview
Howthecompilerworks?
Compilationprocess
Source
file
Preprocessing
Toexpand
macros
Fromsourcecodeto
Compilation
assemblylanguage
Assembly
Executable
file
To create the
linking
finalexecutable
GCCreview
Howthecompilerworks?
Example
Sourcefile:hello.c
#include<stdio.h>
intmain(void)
{
printf("Hello,world!\n");
return0;
}
Preprocessing
$cpphello.c>hello.i
To expand macros and
includedheaderfiles
hello.i:containsthesourcecode
withallmacrosexpanded.
Note:Inpractice,thepreprocessedfileisnotsavedtodisk
unlessthesavetempsoptionisused.
GCCreview
Howthecompilerworks?
Compilation
Example
$gccWallShello.i
Preprocessing
hello.i
hello.s:Fileinassemblylanguage
GCCreview
Howthecompilerworks?
Example
Compilation
hello.s
Assembly
$ashello.sohello.o
To convert assembly language into
machinecodeandgenerateanobjectfile.
The output file is specified with the o
option
GCCreview
Howthecompilerworks?
Example
Assembly
hello.s
Linking
$ ld dynamiclinker /lib/ldlinux.so.2
/usr/lib/crt1.o /usr/lib/crti.o /usr/lib/gcc
lib/i686/3.3.1/crtbegin.o
L/usr/lib/gcc
lib/i686/3.3.1 hello.o lgcc lgcc_eh lc lgcc
lgcc_eh/usr/lib/gcclib/i686/3.3.1/crtend.o
/usr/lib/crtn.o
Linkingofobjectfilestocreateanexecutable
Anexecutablerequiresmanyexternalfunctionsfromsystem
andCruntime(crt)libraries.Consequently,theactuallink
commandsusedinternallybyGCCarecomplicated
GCCreview
Howthecompilerworks?
Example
Assembly
hello.s
Fortunatelythereisneveranyneedtotypethe
commandabovedirectlytheentirelinkingprocess
ishandledtransparentlybygcc
Linking
$gcchello.o
Linkstheobjectfilehello.ototheCstandard
library,andproducesanexecutablefilea.out
Executablefile
$./a.out
Hello,world!