后端开发核心技术 第4章编译 makefile的撰写

普通makefile编写

准备三个文件:file1.h,file1.cpp,file2.cpp

file.h
#ifndef FILE1_H_
#define FILE1_H_
#ifdef __cplusplus
    extern "C" {
       #endif
       void File1Print();
       #ifdef __cplusplus
    }
    #endif
#endif

file1.cpp
#include <iostream>
#include "file1.h"
using namespace std;
void File1Print(){
    cout<<"Print file1**********************"<<endl;
}

file2.cpp
#include <iostream>
#include "file1.h"
using namespace std;
int main(){
    cout<<"Print file2**********************"<<endl;
    File1Print();
    return 0;
}

普通makefile编写

helloworld:file1.o file2.o
	g++ file1.o file2.o -o helloworld

file2.o:file2.cpp
	g++ -c file2.cpp -o file2.o

file1.o:file1.cpp file1.h
	g++ -c file1.cpp -o file1.o

clean:
	rm -rf *.o helloworld

在makegile中使用变量

OBJS = file1.o file2.o
XX = g++
CFLAGS = -Wall -O -g

helloworld : $(OBJS)
	$(XX) $(OBJS) -o helloworld

file2.o : file2.cpp file1.h
	$(XX) $(CFLAGS) -c file2.cpp -o file2.o

file1.o : file1.cpp file1.h
	$(XX) $(CFLAGS) -c file1.cpp -o file1.o

clean:
	rm -rf *.o helloworld

CFLAGS = -Wall -O -g

配置编译器设置,并把它复制给CFLAGS
一、-Wall输出所有的警告信息
二、-O编译时进行优化
三、-g编译debug版本
没添加一个c文件,都需要修改makefile文件

在makefile里使用函数

CC = gcc
XX = g++
CFLAGS = -Wall -O -g
TARGET = helloworld

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

%.o:%.cpp
	$(XX) $(CFLAGS) -c $< -o $@

SOURCES = $(wildcard *.c *.cpp)
OBJS = $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SOURCES)))

$(TARGET) : $(OBJS)
	$(XX) $(OBJS) -o $(TARGET)
clean:
	rm -rf *.o helloworld

SOURCES = $(wildcard *.c *.cpp)

将所有的以.c、.cpp结尾的文件的列表,存放到变量SOURCES里

patsubst

用于函数替换
OBJS = ( p a t s u b s t (patsubst %.c,%.o, (patsubst(patsubst %.cpp,%.o,$(SOURCES)))将文件列表中的所有.c、.cpp字符变换成.o形成一个新的文件列表,存入OBJS变量中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值