A Makefile with Multiple Executables

前端 未结 4 1188
独厮守ぢ
独厮守ぢ 2020-11-22 13:48

I am trying to write a makefile which uses macros to create multiple executables from multiple files at once. I tried searching through previously answered questions but, be

4条回答
  •  渐次进展
    2020-11-22 14:13

    Some suggestions (assuming you use GNU make, not something else)

    First, run once make -p, you'll understand what builtin rules make is knowing. Look in particular for COMPILE.c and LINK.c

    Then, I suggest

     CFLAGS= -g -Wall -I.
    

    (because you really want -g for debugging, and -Wall to get most warnings)

    And you probably don't need

    $(EXECUTABLE): $(OBJ)
        gcc -o $@ $^ $(CFLAGS)
    

    However, I suggest adding before most other rules

    .PHONY: all clean
    
    all: $(EXECUTABLES)
    

    Actually, I would code your Makefile (for GNU make!) as follow

    # file Makefile
    CC= gcc
    RM= rm -vf
    CFLAGS= -Wall -g
    CPPFLAGS= -I.
    SRCFILES= ex1.c ex2.c ## or perhaps $(wildcard *.c)
    OBJFILES= $(patsubst %.c, %.o, $(SRCFILES))
    PROGFILES= $(patsubst %.c, %, $(SRCFILES))
    
    .PHONY: all clean
    
    all: $(PROGFILES)
    clean:
         $(RM) $(OBJFILES) $(PROGFILES) *~
    ## eof Makefile
    

    Remember that tab is a significant character in Makefile-s (action part of rules). In this answer, lines starting with four spaces at least should really start with a tab character.

    Once everything is debugged consider running make clean to clean everything, and then make -j CFLAGS=-O2 all to compile in parallel everything with optimizations.

    At last, I recommend using remake and running remake -x to debug complex Makefile-s

    Of course, I'm supposing that your directory has only single-file programs.

    BTW, there are other build automation tools. Perhaps you might consider using omake or ninja. For building large programs (millions of source code lines) consider also automake, ccache, cmake, icecream. In some cases, consider generating some C code with GPP, GNU bison, SWIG, etc... or using your own Python or Guile script (or C meta-program). See also this draft report.

    Don't forget to use a version control system like git for your source files. It is also time to learn such a tool.

提交回复
热议问题