1. 13


I wanted to share a makefile that I have been using for multifile C projects that produce a single binary program. I included a simple hello world example so that it’s easy to test this out.

The way it works is you list all your .c files in SOURCES=main.c greet.c and it makes targets that compile them into .o object files. It also has a target called main which links all the objects together to make the final program.

If you change one of the .c files it will recompile just that one object file before linking them all together to rebuild the binary. This helps a good fast workflow.

Hope it’s useful! I have been using this as a base for most of my projects. It can be used for other languages than C too if you edit it a little.


  2. 5

    You can remove the %.o rule. The default implicit rule does approximately the same.

    1. [Comment removed by author]

      1. 1

        There’s also one for .s, calling $(AS) with $(ASFLAGS). But yes, it’s useful for other details.

        Here’s a really minimalistic one I have, and a somewhat bigger one. Both work for BSD make and gmake.

        EDIT: Oh, and you may want to prepend the rm with a dash, so it wouldn’t fail on a clean directory.

        1. 4

          My favorite is using no makefile and just doing make blah with a blah.c file. Yes it doesn’t scale but for simple things I just hate typing cc ….. in

          +1 on the leading - for rm.

    2. 2

      Makefiles that don’t handle dependencies properly lead only to the tearing of hair and the gnashing of teeth.

      (See the -M* flags supported by both gcc and clang.)

      1. 1

        In the “somewhat bigger” Makefile I linked above, I solved the dependency problem thusly:

        $(OBJS): $(HDRS)

        One problem in writing portable (between BSD and GNU make) Makefiles is that there’s no common way to include files, and only BSD make includes .depend by default if it exists.

        I dislike gmake.

      2. -2

        eeh, I like CMake better

        1. [Comment removed by author]

          1. 1

            More sane syntax (long make files are nightmare), you can generate a project to various compilers just from 20~ like CMakeFile.