📜  cmake vs makefile (1)

📅  最后修改于: 2023-12-03 14:40:07.088000             🧑  作者: Mango

CMake vs Makefile

CMake and Makefile are both tools used in building software projects. They both serve the purpose of automating the build process, but they differ in how they achieve that end.

Makefile

Makefile is a software tool for building applications automatically from source code by reading files called makefiles. The make tool takes a makefile and creates a dependency graph of the targets that need to be built, then invokes the necessary commands to build them. Makefile provides a way to only build portions of a project that have changed, saving time on large projects, and allowing multiple builds to be done in parallel.

Makefile has been around for over four decades and it is still widely used, especially in Unix-based systems. However, it is notorious for being difficult to read and write.

Here is an example of a Makefile:

CC=gcc
CFLAGS=-I.

all: hello

hello: main.o hello.o
	$(CC) -o hello main.o hello.o

main.o: main.c hello.h
	$(CC) -c -o main.o main.c $(CFLAGS)

hello.o: hello.c hello.h
	$(CC) -c -o hello.o hello.c $(CFLAGS)

clean:
	rm -f *.o hello

This Makefile specifies three targets: all, hello, and clean. The all target is the default target and is executed when no target is specified. The hello target is used to build the executable, and it depends on the main.o and hello.o object files. The clean target is used to remove the object files and the executable.

CMake

CMake is a cross-platform build system generator. It uses a language similar in syntax to Makefile, but with higher-level concepts and improved readability. CMake generates the Makefiles for you.

CMake allows developers to define the target operating systems, their compilers, and the libraries that are required. It also provides an easy-to-read syntax for configuring and building the project, and supports a wide range of build tools, including Makefile, Ninja, and Visual Studio.

Here is an example of a CMakeLists.txt file:

cmake_minimum_required(VERSION 3.10)

project(hello)

set(CMAKE_C_STANDARD 11)

add_executable(hello main.c hello.c hello.h)

This CMakeLists.txt file defines the project name, sets the C standard to version 11, and adds an executable target called hello.

Conclusion

Both CMake and Makefile are useful tools for building software projects. However, while Makefile provides a reliable way of building projects, it can be difficult to read and write. CMake, on the other hand, provides higher-level concepts and an easy-to-read syntax for configuring and building the project. CMake has gained popularity for its cross-platform compatibility and ability to generate Makefiles automatically.