这篇文章演示多目录,c,c++混编的Makefile写法。
文件夹:
$dir/bin/
$dir/deps/
deps/inc/
deps/lib/
deps/src/
$dir/obj/
$dir/project/
project/test.mk
$dir/src/
src/class1.cpp
src/class1.h
src/test.cpp
src/mydir/class2.cpp
src/mydir/class2.h
src/mydir/funs1.c
src/mydir/funs1.h
class1.h:
#ifndef __CLASS_1_h__ #define __CLASS_1_h__ class CTest1 { public: CTest1(); ~CTest1(); int get_v1(); private: int m_v1; }; #endif
class1.cpp:
#include "class1.h" CTest1::CTest1() { m_v1 = 0; } CTest1::~CTest1() { } int CTest1::get_v1() { return m_v1; }
mydir/class2.h:
#ifndef __CLASS_2_h__ #define __CLASS_2_h__ class CTest2 { public: CTest2(); ~CTest2(); int get_v1(); private: int m_v1; }; #endif
mydir/class2.cpp:
#include "class2.h" CTest2::CTest2() { m_v1 = 0; } CTest2::~CTest2() { } int CTest2::get_v1() { return m_v1; }
mydir/funs1.h:
#ifndef __FUNS1_H__ #define __FUNS1_H__ void print1(); #endif
mydir/funs1.c:
#include "funs1.h" #include <stdio.h> void print1() { printf("this is print1\n"); }
test.cpp:
//#define __STDC_LIMIT_MACROS #include <stdint.h> #include <iostream> #include "class1.h" #include "mydir/class2.h" extern "C" { #include "mydir/funs1.h" } int main() { CTest1 test1; CTest2 test2; int a = 127; int16_t b = 128; print1(); std::cout << "max int=" << INT32_MAX << std::endl; std::cout << "test1.v1 = " << test1.get_v1() << std::endl; return 1; }
test.mk:
CFLAGS = -g -Wall -I../src -I../src/mydir -D __STDC_LIMIT_MACROS CC = gcc GXX = g++ #VPATH = ../src ../src/mydir SRCPATH = ../src OBJPATH = ../obj BINPATH = ../bin PROGRAM = test.exe OBJS= class1.o class2.o funs1.o test.o PROGRAMFULL = $(addprefix $(BINPATH)/, $(PROGRAM)) OBJSFULL = $(addprefix $(OBJPATH)/, $(OBJS)) .PHONY: all clean cleanobj show all: clean $(PROGRAMFULL) ${PROGRAMFULL} : ${OBJSFULL} $(GXX) -o $@ $(OBJSFULL) ${OBJPATH}/%.o : ${SRCPATH}/mydir/%.c $(CC) $(CFLAGS) -c $< -o $@ ${OBJPATH}/%.o : ${SRCPATH}/mydir/%.cpp $(GXX) $(CFLAGS) -c $< -o $@ ${OBJPATH}/%.o : ${SRCPATH}/%.cpp $(GXX) $(CFLAGS) -c $< -o $@ clean: rm -f ${PROGRAMFULL} ${OBJSFULL} cleanobj: rm -f ${OBJSFULL} show: @echo 'PROGRAMFULL :' ${PROGRAMFULL} @echo 'OBJSFULL :' $(OBJSFULL) @echo 'CFLAGS :' $(CFLAGS)