'make clean failed in windows

I want to use mingw to compile my C language project.

I found the command of make all succeeded, however make clean failed. There are only two files in my test project: test.c and Makefile.mak.

test.c:

#include <stdio.h>

int main()
{
    printf("Hello world\n");
    while (1);

    return 0;
}

Makefile.mak:

all: test.o
    gcc test.o -o test.exe

test.o: test.c
    gcc -c test.c

clean:
    @echo "clean project"
    -rm test *.o
    @echo "clean completed"
.PHONY: clean

When I ran make all -f Makefile.mak, it succeeded and generated the expected test.exe, and I also can run the executable. However, when I run make clean -f Makefile.mak, it failed, the error is:

"clean project"
rm test *.o
process_begin: CreateProcess(NULL, rm test *.o, ...) failed.
make (e=2):
Makefile.mak:8: recipe for target 'clean' failed
make: [clean] Error 2 (ignored)
"clean completed"

Why?

EDIT:

The following link enlightened me: MinGW makefile with or without MSYS (del vs rm)

  1. I added the workaround code mentioned in the above link in my makefile:
ifeq ($(OS),Windows_NT) 
RM = del /Q /F
CP = copy /Y
ifdef ComSpec
SHELL := $(ComSpec)
endif
ifdef COMSPEC
SHELL := $(COMSPEC)
endif
else
RM = rm -rf
CP = cp -f
endif

all: test.o
    gcc test.o -o test.exe

test.o: test.c
    gcc -c test.c

clean:
    @echo "clean project"
    -$(RM) test.exe *.o
    @echo "clean completed"
.PHONY: clean

It works:

"clean project"
del /Q /F test.exe *.o
"clean completed"
  1. This reminds me that it may be because current environment doesn't support rm command, so I add my msys install path into environment path, then it works:
clean project
rm test.exe *.o
clean completed


Solution 1:[1]

Try this one:

'make clean' not working

Clean in MinGW by default will run -rm command. But this command is not supported by window. Window use del.

So you need to edit makefile with notepad++, change

clean:
    -rm -fR $(BUILD_DIR)

To

clean:
    -del -fR $(BUILD_DIR)

Solution 2:[2]

You're trying to remove a file called "test" but no such file exists. As a result, the rm command fails.

You want to delete "test.exe", as that is the name of your output file. Also, you should use the -f option to rm, as that will 1) do a forced remove, and 2) won't fail if the file doesn't exist:

clean:
    @echo "clean project"
    -rm -f test.exe *.o
    @echo "clean completed"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zmag
Solution 2 dbush