Simple Makefile

At times you may need to test some rather simple code. You could just use the commands in the shell which will soon become a pain as you try to clean and recompile the test code. Instead, a Makefile would be handy.

Build over simplified

The process of creating native applications/libraries (in C/C++) essentially consists of the following.

  1. Compile each source file (.c or .cpp) to an object file (.o or.obj)
  2. gcc -o test.o -c test.cpp
  3. Link all the object files and dependent libraries
  4. gcc -o test test.o -lstdc++

These compilation and link steps can be combined into a “script” called a Makefile.

Makefile

The Makefile shown below (and associated sources) can be accessed from GitHub https://github.com/cognitivewaves/Simple-Makefile

# Specify compiler
CC=gcc

# Specify linker
LINK=gcc

.PHONY : all
all : app

# Link the object files into a binary
app : main.o
	$(LINK) -o app main.o -lstdc++

# Compile the source files into object files
main.o : main.cpp
	$(CC) -c main.cpp -o main.o

# Clean target
.PHONY : clean
clean :
	rm main.o app 

Conclusion

As mentioned earlier, this is an extremely simple example. More details can be found at Makefiles and Visual Studio, especially if you are coming from a Visual Studio background.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s