# 一個基礎示例 makefile_test
main.cpp
#include "print.h"
int main()
{
printhello();
return 0;
}
print.h
#include<stdio.h>
void printhello();
print.cpp
#include"print.h"
void printhello()
{
printf("Hello, world\n");
}
Makefile
# #*********基礎版
# helloworld:main.o print.o
# gcc -o helloworld main.o print.o
# mian.o:mian.c print.h
# gcc -c main.c
# print.o:print.c print.h
# gcc -c print.c
# clean:
# rm helloworld main.o print.o
# #*********簡化版
obj := main.o print.o # 變量;宏定義
helloworld:$(obj)
gcc -o helloworld $(obj)
$(obj):print.h # 都依賴print.h
mian.o:mian.c #去掉了gcc -c main.c 讓gcc make自動推導
print.o:print.c
clean:
rm helloworld $(obj)
# 報錯、異常處理
- makefile老是報“recipe for target xxx”錯誤,不妨先看看makefile文件的編碼是否正確
如果你的makefile是直接從網上覆制來的,先在window下,用寫字板看看是否有亂碼,“空格”的亂碼很有可能就是你錯誤的罪魁禍首。
- 在函數‘_start’中:對‘main’未定義的引用
這是因爲,編譯的文件中,找不到main()這個函數.
確認一下,是不是註釋了,或者ifdef沒了.或者包含main的.cpp文件未被包含生成.o文件
# 相關教程、示例資料
《跟我一起寫Makefile》
鏈接:https://pan.baidu.com/s/1OT-Hk3bzo070hjuWo39ASg
提取碼:sjfy
一個Makefile示例; 採用了很多高級功能,大大簡化了makefile文件的編寫
https://www.jianshu.com/p/3c13d915dcb0
完整的示例工程和 makefile 文件可以到如下路徑取:
https://github.com/Lingminzou/code/tree/master/makefile/example
make的使用和Makefile的編寫
https://blog.csdn.net/u012510204/article/details/53926399
跟我一起寫Makefile
https://seisman.github.io/how-to-write-makefile/overview.html
自動生成項目的Makefile文件(待研究)
https://www.cnblogs.com/yejinru/p/4983209.html
vs code 配置.json文件引入makefile文件實現多文件編譯
https://blog.csdn.net/m0_37433067/article/details/80145679
# 一個較通用模板
Makefile
# //*** 根據具體工程需要,更改BINNAME、LD_OPTS、SRC_DIR 、CC_OPTS等宏變量即可 ***//
# 輸出標目名稱
BINNAME = UnderdriveHand
# 設置 .o 文件輸出路徑
OBJDIR = ./obj
# 配置工具鏈 CC
CC = g++
# 配置編譯選項
CC_OPTS := -std=c++11 # -Wall -Werror 編譯過程中輸出控制
# 配置鏈接選項
LD_OPTS := -lpthread
# 指定編譯時依賴的頭文件目錄,然後放進編譯選項
INC_DIR := ./EigenArduino_Eigen30 # ./serial ./driver ./kinematic ./control 如何連續包含??
CC_OPTS += -I$(INC_DIR)
CC_OPTS += -I ./drive
CC_OPTS += -I ./kinematic
CC_OPTS += -I ./control
CC_OPTS += -I ./main
# 指出源文件存放路徑
SRC_DIR := ./EigenArduino_Eigen30
SRC_DIR += ./drive ./kinematic ./control ./main
# 指定依賴文件搜索路徑,即我們的源文件路徑
VPATH = $(SRC_DIR)
# 找出所有需要編譯的 cpp 類型文件,注意 find 默認是會循環找子目錄的,
# 由於我們子目錄的路徑也需要寫進 VPATH 所以這裏把 find 的查找深度設置爲了 1
SRC = $(shell find $(SRC_DIR) -maxdepth 1 -name '*.cpp') # -maxdepth 1
# 生成需要輸出的 .o 文件名
OBJ_0 = $(notdir $(patsubst %.cpp, %.o, $(SRC)))
# 加上 .o 文件存放路徑前綴
OBJ = $(foreach file, $(OBJ_0), $(OBJDIR)/$(file))
.PHONY: all setup bin clean
all: setup bin
setup:
@echo $(SRC)
@echo $(OBJ_0)
@echo $(OBJ)
mkdir -p $(OBJDIR)
bin: $(OBJ)
$(CC) $(OBJ) $(LD_OPTS) -o $(BINNAME)
$(OBJ): $(OBJDIR)/%.o : %.cpp
$(CC) $(CC_OPTS) -o $@ -c $<
clean:
rm -rf $(OBJDIR)
rm -rf $(BINNAME)
根據具體工程需要,更改BINNAME、LD_OPTS、SRC_DIR 、CC_OPTS等宏變量即可.