Scaparra.com

Be incomprehensible. If they can’t understand, they can’t disagree.
Archive for June 8th, 2008

Programming with multiple files.

A friend of mine asked me today about this topic so in case I am asked about it in the future I am posting my response here.

Sometimes when writing an application in C++, C, Java, etc… if is nice to separate functionality of the program into different modules, i.e. files. This is absolutely necessary in larger programs. The following is an example of hello world spread out into two .cpp files and one .h.

main.cpp

#include “printFunctions.h” // this is where printMessage() is defined

int main()
{
printMessage();
return 0;
}

printFunctions.cpp

#include “printFunctions.h”

void printMessage( )
{

std::cout << “Hello World” << std::endl;

}

printFunctions.h


#ifndef PRINT_FUNCTIONS_H
#define PRINT_FUNCTIONS_H

#include<iostream>

void printMessage();

#endif

makefile


OBJS=main.o printFunctions.o
CC=g++
CXXFLAGS=-ggdb -g3 -g -O2 -Wall
DEPEND= makedepend $(CFLAGS)

helloWorld: $(OBJS)
$(CC) $(LDFLAGS) -o $@ $(OBJS)

clean:
-rm *.o helloWorld

And that is all there is to it. We can use the make file to compile the program in the following manner:

scap@Earth ~/example $ make
g++ -ggdb -g3 -g -O2 -Wall   -c -o main.o main.cpp
g++ -ggdb -g3 -g -O2 -Wall   -c -o printFunctions.o printFunctions.cpp
g++  -o helloWorld main.o printFunctions.o
scap@Earth ~/example $ ./helloWorld
Hello World
scap@Earth ~/example $ make clean
rm *.o helloWorld
scap@Earth ~/example $

Here are the Example Files. Just run tar xzvf exampletar.gz to unpack.

Jeff

1 comment

Guitar Hero in DC!!

Late last night I was challenge into some guitar hero!! We beat the game on medium and we are working our way through hard! Anyways in true scaparra fashion busted out the camera and had a little fun.

No comments