Search code examples
cmakefile

Missing separator in Makefile?


The following Makefile is not working and I am not sure what's going on.

CC = gcc
CFLAGS = -Wall -g

demo:
    ${CC} ${CFLAGS} demo.c -o demo
lib:
    ${CC} ${CFLAGS} lib.c -o lib
clean:
    rm -f lib demo

Demo has the main function and lib has a set of methods used in demo.

I added the -c flag to lib. However when I run make, I get:

Makefile:5: *** missing separator.  Stop.

Solution

  • Given your update with the error, check what you have on the line before those ${CC} commands. Many make programs require a real tab character before the commands and editors that put in eight spaces (for example) will break them. That's more often than not the cause of the "Missing separator" errors.

    You can see that with the following transcript. In the file, there are four spaces before the $(xyzzy):

    xyzzy=echo
    all:
        $(xyzzy) hello
    

    So, when I make it, I get the same error as you:

    pax> make
    makefile:3: *** missing separator.  Stop.
    

    But, when I edit it and turn those four spaces into a tab, it works fine:

    pax> make
    echo hello
    hello
    

    You also have a problem with the way you're trying to combine the source files together.

    Without a -c flag to gcc, it will try to create a separate executable from each of those commands, almost certainly leading to linker errors. You're going to need something like (simple):

    CC = gcc
    CFLAGS = -Wall -g
    
    # Just compile/link all files in one hit.
    demo: demo.c lib.c
       ${CC} ${CFLAGS} -o demo demo.c lib.c
    
    clean:
        rm -f demo
    

    or (slightly more complex):

    CC = gcc
    CFLAGS1 = -Wall -g -c
    CFLAGS2 = -g
    
    # Link the two object files together.
    
    demo: demo.o lib.o
       ${CC} ${CFLAGS2} -o demo demo.o lib.o
    
    # Compile each source file to an object.
    
    demo.o: demo.c
       ${CC} ${CFLAGS1} -o demo.o demo.c
    
    lib.o: lib.c
       ${CC} ${CFLAGS1} -o lib.o lib.c
    
    clean:
        rm -f demo
    

    The problem with the first solution is that it unnecessarily compiles both programs even when only one is out of date. The second solution is a little more intelligent.