About writing Makefile files and Cmake

*(This post is a summary of learning, please refer to it with caution)*
Suppose we have the following three files hellomake.c, hellofunc.c, hellomake.h.
If you do not write a makefile file, you need to compile it directly in the terminal when compiling. This method is Insufficient (province)

//    gcc -o 编译后的程序名 需要编译的.c文件 编译标志
//(注意每个gcc前面都应该有一个Tab)
//例如:
    gcc -o hellomake hellomake.o hellofunc.o -I.

Therefore, you can build a makefile to define the compilation rules in advance, and then execute it directly with the make command. The simplest makefile can be written as follows (assuming that the files are all in the current directory):

//假设这些文件都在当前目录
hellomake: hellomake.o hellofun.o //冒号左边是目标程序,右边是生成目标文件所需要的依赖文件
    gcc -o hellomake hellomake.o hellofun.o -I. //-I.表示从当前目录获取头文件
hellomake.o: hellomake.c //书写每个.o文件的规则
    gcc -c hellomake.c
hellofun.o: hellofun.c
    gcc -c hellofun.c

In addition to using the simple writing method of makefile , it can also be like this after optimization:

IDIR = ../include 
CC=gcc //定义编译器
CFLAGS=-I$(IDIR) //定义读取头文件的地址,默认是-I.。

ODIR=obj //可以设置.o文件的目录
LDIR=../lib

LIBS=-lm //定义math库

_DEPS=hellomake.h
DEPS=$(pathsubst %,$(IDIR)/%,$(_DEPS)) //头文件(包含路径)

_OBJ= hellomake.o hellofunc.o
OBJ = $(pathsubst %,$(ODIR)/%,$(_OBJ)) //生成的.o文件(包含路径)

hellomake:$(OBJ)
    $(CC) -o $@ $^ $(CFLAGS) $(LIBS) //$@ $^分别表示:左边和右边  $^表示规则中所有依赖
$(ODIR)/%.o:%.c $(DEPS)
    $(CC) -c $< -o $@ $(CFLAGS) //$@表示将输出文件命名为:左边的文件名, $<表示依赖列表中的第一个项
    
.PHONY:clean //.PHONY规则可以让make不去改动任何名为clean的文件(如果有的话)
clean:
    rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~  //文件清理

Cmake tools

CMake (Cross platform Make) is an open source cross-platform automated build tool that can generate a variety of makefiles or project files across platforms, and supports the use of various compilation tools to generate executable programs or link libraries.

Generally, makefile files are relatively complex, and it is troublesome to write them yourself. However, using CMake, you can write a relatively simple CMakeLists.txt. CMakeLists.txt needs to be written manually , or it can be generated semi-automatically by writing a Python script . CMake automatically generates a makefile based on CMakeLists.txt, and then you can use make to generate an executable program or link library.

cmake_minimum_required (VERSION 2.8) //版本号

project (demo) //工程名

//注意aux_source_directory和set二选一就行

set( SRC_LIST
     ./main.c
     ./hellofun.c
     ./hellomake.c) //set可以将依赖文件统一放在SRC_LIST下面


add_executable(hellomake ${SRC_LIST}) //main是待生成的主程序文件 ${SRC_LIST}是依赖文件
cmake_minimum_required (VERSION 2.8) //版本号

project (demo) //工程名

//注意aux_source_directory和set二选一就行

aux_source_directory(. SRC_LIST) //默认当前目录文件下除.txt以外的其他文件都是需要放在SRC_LIST里的,如果有一部分文件不需要,则可以用set来指定文件

add_executable(hellomake ${SRC_LIST}) //main是待生成的主程序文件 ${SRC_LIST}是依赖文件

Guess you like

Origin blog.csdn.net/new_0428/article/details/129974946