Simple Test Unix C++ Source Compilation and Makefile

Create 3 (*.C) files

/* main.C */
#include <stdlib.h>
#include "1.h"

extern void test2();
extern void test3();

void test1()

int main()


/* 2.C */
#include "1.h"
#include "2.h"

void test2() {
/* 3.C */
#include "2.h"
#include "3.h"
void test3() {

Create 3 (*.h) files
touch 1.h
touch 2.h
touch 3.h


Create a makefile with content (note: <tab> should be a real tab. Tab is very important or else you will else funny compiler message)

testing123: main.o 2.o 3.o
<tab>g++ -o myapp main.o 2.o 3.o
main.o: main.C 1.h
<tab>g++ -c main.C

2.o: 2.C 1.h 2.h
<tab>g++ -c 2.C

3.o: 3.C 2.h 3.h
<tab>g++ -c 3.C

Then run

make -f makefile


export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/apps/public/lib

(for C++ libraries since g++ is to compile CPP files)

Then, just run "testing123"

(note: In Unix, *. a is a static library where as *.so or *.sa is a shared library or dynamic DLL in Win32 term. To make the link to shared library permanently link to the binary. Use the configuration option --disable-shared)

To modify makefile above to create static lib file, makefile command as below
# Which compiler
CC = g++

# Where are include files kept

# Options for development
CFLAGS = -g -Wall -ansi

# Local Libraries
MYLIB = lib.a

testing123: main.o $(MYLIB)
$(CC) -o testing123 main.o $(MYLIB) $(CFLAGS)

$(MYLIB): $(MYLIB)(2.o) $(MYLIB)(3.o)
main.o: main.C a.h
2.o: 2.C 1.h 2.h
3.o: 3.C 2.h 3.h

-rm testing123 main.o 2.o 3.o $(MYLIB)


Popular posts from this blog

Clearcase check in/uncheck out all the checked out files script


Duplicating a local copy of project from TFS and making web software client factory to work