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

One Comment

  1. Posted November 9, 2008 at 9:09 PM | Permalink

    People should read this.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*