compile headers dependencies with makefile

后端 未结 2 712
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-13 15:47

I am programming an UDP client server application in the C programming language; I want to automatically compile 2 sources files and 3 header files whenever the dependencies

2条回答
  •  忘掉有多难
    2021-01-13 16:25

    I think what you want are Make dependency files.

    You can specify the compiler to generate a dependency file for you with the '-MMD -MP' arguments, which create a new file with the same name as the source file except with the extension *.d, in the same folder as your source.

    The dependency file contains all the headers the code depends on, which will lead to GNU make compiling your source file if a header it uses is modified.

    An example dependency file enabled makefile:

    # Makefile
    
    CC   := gcc
    LD   := g++
    
    # The output executable.
    BIN   := program
    
    # Toolchain arguments.
    CFLAGS    := 
    CXXFLAGS  := $(CFLAGS)
    LDFLAGS   := 
    
    # Project sources.
    C_SOURCE_FILES := mysourcefile1.c src/myothersrc.c
    C_OBJECT_FILES := $(patsubst %.c,%.o,$(C_SOURCE_FILES))
    
    # The dependency file names.
    DEPS := $(C_OBJECT_FILES:.o=.d)
    
    all: $(BIN)
    
    clean:
        $(RM) $(C_OBJECT_FILES) $(DEPS) $(BIN)
    
    rebuild: clean all
    
    $(BIN): $(C_OBJECT_FILES)
        $(LD) $(C_OBJECT_FILES) $(LDFLAGS) -o $@
    
    %.o: %.c
        $(CC) -c -MMD -MP $< -o $@ $(CFLAGS)
    
    # Let make read the dependency files and handle them.
    -include $(DEPS)
    

    This should work for your situation:

    SOURCES := server_UDP.c client_UDP.c
    OBJECTS := $(patsubst %.c,%.o,$(SOURCES))
    
    DEPS := $(OBJECTS:.o=.d)
    
    edit: $(OBJECTS)
        gcc -o edit $(OBJECTS)
    
    %.o: %.c
        gcc -c $< -o $@
    
    -include $(DEPS)
    

提交回复
热议问题