path include and src directory makefile

后端 未结 3 1363
不知归路
不知归路 2021-01-30 07:58

Following this tutorial:

http://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/

It has 3 files 2 of which are .c files and 1 .h fil

3条回答
  •  滥情空心
    2021-01-30 08:16

    the make utility, with no specific 'target' will make the first target in the file.

    The first target is usually named 'all'

    For the posted file, will make the object files and will not continue to make the executable when the target is not given in the command line

    Suggest the following:

    SHELL := /bin/sh
    
    # following so could define executable name on command line
    # using the '-D' parameter
    #ifndef $(NAME)
        NAME := hellomake
    #endif
    
    # use ':=' so macros only evaluated once
    
    
    MAKE    :=  /usr/bin/make
    CC      :=  /usr/bin/gcc
    
    CFLAGS  := -g -Wall -Wextra -pedantic
    LFLAGS  :=
    
    ODIR    := obj
    IDIR    := ../include
    LIBS    :=
    LIBPATH := ../lib
    
    DEPS    := $(wildcard $(IDIR)/*.h)
    SRCS    := $(wildcard *.c)
    OBJS    := $(SRCS:.c=.o)
    
    .PHONY: all
    all: $(NAME) $(OBJS)
    
    $(ODIR)/%.o: %.c $(DEPS)
        $(CC) $(CFLAGS) -c -o $@ $< -I$(DEPS)
    
    $(NAME): $(OBJS)
        $(CC) $(LFLAGS) -o $@ $^ -L$(LIBPATH) -l$(LIBS)
    
    .PHONY: clean
    clean:
        rm -f $(ODIR)/*.o
        rm -f $(NAME)
    
    
    however, in your proposed project,
    not every source file needs every header file
    so should use either gcc or sed to generate the dependency files
    then use makefile rules similar to the following,
    which may need a little 'tweaking' for your project
    because the include files are not in the same directory
    as the source files:
    
    DEP := $(SRCS:.c=.d)
    
    #
    #create dependency files
    #
    %.d: %.c 
        # 
        # ========= START $< TO $@ =========
        $(CC) -M $(CPPFLAGS) $< > $@.$$$$;                      \
        sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@;     \
        rm -f $@.$$$$
        # ========= END $< TO $@ =========
    
    # 
    # compile the .c files into .o files using the compiler flags
    #
    %.o: %.c %.d 
         # 
         # ========= START $< TO $@ =========
         $(CC) $(CCFLAGS) -c $< -o $@ -I$(IDIR) 
         # ========= END $< TO $@ =========
         # 
    
    # include the contents of all the .d files
    # note: the .d files contain:
    # .o:.c plus all the dependencies for that .c file 
    # I.E. the #include'd header files
    # wrap with ifneg... so will not rebuild *.d files when goal is 'clean'
    #
    ifneq "$(MAKECMDGOALS)" "clean"
    -include $(DEP)
    endif
    

提交回复
热议问题