You are on page 1of 2

Search

OnlineGuides <<<previous tableofcontents next>>>


AllGuides
eBookStore
iOS/Android
LinuxforBeginners
2.3Compilingmultiplesourcefiles
OfficeProductivity
LinuxInstallation Aprogramcanbesplitupintomultiplefiles.Thismakesiteasiertoeditandunderstand,
LinuxSecurity especiallyinthecaseoflargeprogramsitalsoallowstheindividualpartstobecompiled
LinuxUtilities independently.
LinuxVirtualization
LinuxKernel InthefollowingexamplewewillsplituptheprogramHelloWorldintothreefiles:'main.c',
System/Network 'hello_fn.c'andtheheaderfile'hello.h'.Hereisthemainprogram'main.c':
Admin
Programming #include"hello.h"
ScriptingLanguages
DevelopmentTools
WebDevelopment int
GUIToolkits/Desktop main(void)
Databases {
MailSystems hello("world");
openSolaris return0;
EclipseDocumentation }
Techotopia.com
Virtuatopia.com
Theoriginalcalltotheprintfsystemfunctioninthepreviousprogram'hello.c'hasbeen
replacedbyacalltoanewexternalfunctionhello,whichwewilldefineinaseparatefile
HowToGuides
Virtualization
'hello_fn.c'.
GeneralSystemAdmin
LinuxSecurity Themainprogramalsoincludestheheaderfile'hello.h'whichwillcontainthedeclaration
LinuxFilesystems ofthefunctionhello.Thedeclarationisusedtoensurethatthetypesoftheargumentsand
WebServers returnvaluematchupcorrectlybetweenthefunctioncallandthefunctiondefinition.Weno
Graphics&Desktop longerneedtoincludethesystemheaderfile'stdio.h'in'main.c'todeclarethefunction
PCHardware
printf,sincethefile'main.c'doesnotcallprintfdirectly.
Windows
ProblemSolutions
Thedeclarationin'hello.h'isasinglelinespecifyingtheprototypeofthefunctionhello:

voidhello(constchar*name);

Thedefinitionofthefunctionhelloitselfiscontainedinthefile'hello_fn.c':


#include<stdio.h>
#include"hello.h"

void
hello(constchar*name)
{
printf("Hello,%s!\n",name);
}

Thisfunctionprintsthemessage"Hello,name!"usingitsargumentasthevalueofname.

Incidentally,thedifferencebetweenthetwoformsoftheincludestatement#include
"FILE.h"and#include<FILE.h>isthattheformersearchesfor'FILE.h'inthecurrent
directorybeforelookinginthesystemheaderfiledirectories.Theincludestatement#include
<FILE.h>searchesthesystemheaderfiles,butdoesnotlookinthecurrentdirectoryby
default.

Tocompilethesesourcefileswithgcc,usethefollowingcommand:

$gccWallmain.chello_fn.conewhello

Inthiscase,weusetheooptiontospecifyadifferentoutputfilefortheexecutable,
'newhello'.Notethattheheaderfile'hello.h'isnotspecifiedinthelistoffilesonthe
commandline.Thedirective#include"hello.h"inthesourcefilesinstructsthecompilerto
includeitautomaticallyattheappropriatepoints.

Toruntheprogram,typethepathnameoftheexecutable:

$./newhello
Hello,world!

Allthepartsoftheprogramhavebeencombinedintoasingleexecutablefile,which
producesthesameresultastheexecutablecreatedfromthesinglesourcefileusedearlier.
<<<previous tableofcontents next>>>


PublishedunderthetermsoftheGNUGeneralPublicLicense DesignbyInterspire

You might also like