温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Makefile实例

发布时间:2020-07-10 23:23:20 来源:网络 阅读:835 作者:TrueDetective 栏目:编程语言

A stupid man think himself is clever. A clever think himself is stupid.


  1. Make基础


先上脚本:

COMPILE = g++
FLAGS = -std=c++11 -g
target = epollserver
objs = client.o clientmanager.o main.o \
savetomysql.o threadable.o
libs = -L -lpthread \
-L/usr/lib/x86_64-linux-gnu  -lmysqlclient \
-L/home/ssx/Boost/boost_1_60_0/to/installation/prefix/lib -lboost_system \
-L/home/ssx/Boost/boost_1_60_0/to/installation/prefix/lib -lboost_thread \
minclude = -I.
$(target) : $(objs)
    g++ -o  $(target) $(objs) $(libs)
client.o : client.cpp
    g++ $(FLAGS) -c $<  $(libs) $(minclude)
clientmanager.o : clientmanager.cpp
    g++ $(FLAGS) -c $<  $(libs) $(minclude)
savetomysql.o : savetomysql.cpp
    g++ $(FLAGS) -c $<  $(libs) $(minclude)
threadable.o : threadable.cpp
    g++ $(FLAGS) -c $<  $(libs) $(minclude)
main.o : main.cpp
    g++ $(FLAGS) -c $<  $(libs) $(minclude)
.PHONY : clean
clean :
    rm $(target) $(objs)



Makefile的原理很简单,最终目标由几个阶段目标连接而成,而各个目标(.o文件) 又是由源文件编译出来的。

在shell中

编译的基本命令是 gcc -c  xx.c / g++ -c xx.cpp

链接的基本命令是 gcc -o xx.o x1.o x2.o

具体还要看你的编译选项,包含文件,包含库,总之就是个shell命令了。


Makefile就是目标+命令的组合,且看这2行:


client.o : client.cpp
    g++ $(FLAGS) -c $<  $(libs) $(minclude)

client.o 是目标 原料是client.cpp 命令是

 g++ $(FLAGS) -c $<  $(libs) $(minclude)


就这么简单。

另外这里定义了一些宏(不是变量!),看起来比较方便,改起来不费劲。

最后的.PHONY : clean ... 是不需要原料,只有命令的目标---伪目标, make clean用到



 

2. Make进阶

# which complier
CC = g++
#where are include file kept
INCLUDE = .
# Options for development
CFLAGS = -std=c++11  -shared -fPIC -Wall
#all the cpp files
SRCS := $(wildcard *.cpp) 
#all the objs
OBJS := $(patsubst %cpp,%o,$(SRCS))
# All the Objects
OBJECTS = public_header.o threadable.o threadsmgr.o

#where are the libs kept
libs = -L -lpthread \
-L/home/ssx/Boost/boost_1_60_0/to/installation/prefix/lib -Wl,-rpath=/home/ssx/Boost/boost_1_60_0/to/installation/prefix/lib  -lboost_system \
-L/home/ssx/Boost/boost_1_60_0/to/installation/prefix/lib -Wl,-rpath=/home/ssx/Boost/boost_1_60_0/to/installation/prefix/lib  -lboost_thread \
 -lglog
#target
target = libsuper_thread.so

#牛逼的递推
%.o:%.cpp
    $(CC)    $(CFLAGS)  -c $< -I. $(libs)



$(target):$(OBJECTS) 
    $(CC) $(CFLAGS) -o $@ $^  -I. $(libs)
clean :
    rm -f $(OBJECTS) $(target)

这个和上一个版本相比更加复杂,但是更加智能化了。


#牛逼的递推
%.o:%.cpp
    $(CC)    $(CFLAGS)  -c $< -I. $(libs)

文件夹里面,每个cpp都会被编译成一个.o  根据这个思路,有了递推写法。


$(target):$(OBJECTS) 
    $(CC) $(CFLAGS) -o $@ $^  -I. $(libs)
    当然objects也可以递推得出:
    
#all the cpp files
SRCS := $(wildcard *.cpp) 
#all the objs
OBJS := $(patsubst %cpp,%o,$(SRCS))
    但不推荐,因为有的.o未必需要被连接上



另外的要点

-L -l 与 -Wl -rpath= 这两组命令都跟依赖库有关,但是-L -l只告诉了编译时候去哪里读库(.so文件), 而-Wl -rpath= 告诉程序运行时去×××.so


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI