How do I make Makefile to recompile only changed files?

前端 未结 3 1277
粉色の甜心
粉色の甜心 2020-12-12 12:41

I have been struggling a bit to get make to compile only the files that have been edited. However I didn\'t have much success and all the files get recompiled. Can someone e

3条回答
  •  心在旅途
    2020-12-12 13:06

    This very late after the fact, and actually it's based on paxdiablo's excellent answer, but while experimenting i found that you don't need separate targets for each .o file unless you're doing something clever.

    So for my makefile:

    all: program
    
    program: a_functions.o main.o
        gcc a_functions.o main.o -o program
    
    clean: 
        rm -f *.o
        rm -f program
    

    In make 4.1 it compiles the .o files automatically, you don't have to do anything if your .o files have the same names as your source files. So, it will go and hunt for a_functions.c, a_functions.h, main.h and main.c automagically. If you don't have the expected source code names, then you'll get an error like:

    make: *** No rule to make target 'a_functions.o', needed by 'program'.  Stop.
    

    I have also added a "clean" target for you. "Clean" is useful if you need to release your software as source code, or you just want to remove all the compiled object files and / or binaries.

    And this is all you need to do.

    Save this to "Makefile" and run:

    $ make
    

    to build your binary. And

    $ make clean 
    

    to clean up the compiled objects and binaries in your code.

提交回复
热议问题