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 https://github.com/cognitivewaves/Simple-Makefile.
Build over simplified
The process of creating native applications/libraries (in C/C++) essentially consists of the following.
- Compile each source file (
.cpp) to an object file (
gcc -o test.o -c test.cpp
- 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
# 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
CMake toolchain uses a similar concept as
Make and has better abstraction. The build steps are saved in
CMakeLists.txt (equivalent of
cmake_minimum_required (VERSION 2.6) project (SimpleCMake) # Compiler flags set(CMAKE_CXX_FLAGS "-std=c++11") # Pre-processor definitions add_definitions() # Paths to include files include_directories() # Specify binary to be created add_executable (app main.cpp) # Paths to dependent libraries link_directories() # 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.