Simple Makefile

At times you may need to test some rather simple code or start a new project. 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 build script would be handy.

The files shown below (and associated sources) can be accessed from GitHub

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)
gcc -o test.o -c test.cpp
  1. Link all the object files and dependent libraries
gcc -o test test.o -lstdc++


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

# Specify compiler

# Specify linker

.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


The CMake toolchain uses a similar concept as Make and has better abstraction. The build steps are saved in CMakeLists.txt (equivalent of Makefile).

cmake_minimum_required (VERSION 2.6)

project (SimpleCMake)

# Compiler flags
set(CMAKE_CXX_FLAGS "-std=c++11")

# Pre-processor definitions

# Paths to include files

# Specify binary to be created
add_executable (app main.cpp)

# Paths to dependent libraries

# Specify dependent libraries
target_link_libraries(app stdc++)


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

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s