随笔 - 51, 文章 - 1, 评论 - 41, 引用 - 0
数据加载中……

带依赖关系的makefile简易例子

# makefile 开始

# 编译相关的选项
CC = g++
CPPFLAG =

# 所有的cpp源文件或者手动添加文件
SOURCES = $(wildcard *.cpp)
#SOURCES = main.cpp \
#          test_func.cpp    \
#          test_class.cpp

# 与源文件对应的目标文件和依赖文件
OBJECTS = $(SOURCES:.cpp=.o)
DEPENDS = $(SOURCES:.cpp=.d)

# 第一个编译模板
all: test.exe


# 添加依赖文件
sinclude $(DEPENDS)


test.exe: $(OBJECTS)
    $(CC) $(OBJECTS) -o test.exe


$(OBJECTS): %.o: %.cpp
    $(CC) -c $(CPPFLAG) $< -o $@


# 生成依赖文件,由于依赖文件也依赖源文件,因此需要增加xxx.d,如:
# main.o: main.cpp test_func.hpp test_class.hpp
# main.d main.o: main.cpp test_func.hpp test_class.hpp
# 一般的例子会使用sed实现这个功能,在这里我编写了print.exe实现该功能。
%.d: %.cpp print.exe
    print.exe $@ > $@
    $(CC) -MM $< >> $@

 

# 辅助生成依赖文件的程序
print.exe: print.c
    $(CC) print.c -o print.exe

 

#清除所有文件
clean:
    del test.exe print.exe $(OBJECTS) $(DEPENDS)

 

#makefile 结束

 

// print.c 开始

#include <cstdio>
int main(int argc, const char* argv[]) {
    if (argc > 1) {
        printf("%s ", argv[1]);
    }
    return 0;
}

// print.c 结束

 

// main.cpp 开始

#include "test_func.hpp"
#include "test_class.hpp"

int main() {
    TestClass::Print();
    Print();
}

// main.cpp 结束

 

// test_class.hpp 开始

#ifndef TEST_CLASS_HPP
#define TEST_CLASS_HPP
class TestClass {
public:
    static void Print();
};

#endif // TEST_CLASS_HPP

// test_class.hpp 结束

 

// test_class.cpp 开始

#include <cstdio>
#include "test_class.hpp"

void TestClass::Print() {
    printf("TestClass\n");
}

// test_class.cpp 结束

 

// test_func.hpp 开始

#ifndef TEST_FUNC_HPP
#define TEST_FUNC_HPP

void Print();

#endif // TEST_FUNC_HPP

// test_func.hpp 结束

 

// test_func.cpp 开始

#include <cstdio>
#include "test_func.hpp"

void Print() {
    printf("TestFunc\n");
}

// test_func.cpp 结束

posted on 2014-05-14 22:34 lemene 阅读(685) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理