Skip to content

Instantly share code, notes, and snippets.

@wkentaro
Last active August 19, 2023 13:33
Show Gist options
  • Save wkentaro/4156dfc7922437a9ff60 to your computer and use it in GitHub Desktop.
Save wkentaro/4156dfc7922437a9ff60 to your computer and use it in GitHub Desktop.
Makefile to compile all c files in the directories
CC :=gcc
CPP :=g++
LDFLAGS :=
C_SOURCES :=$(wildcard *.c)
C_EXECUTABLE :=$(C_SOURCES:.c=)
CPP_SOURCES :=$(wildcard *.cpp)
CPP_EXECUTABLE :=$(CPP_SOURCES:.cpp=)
all:$(C_EXECUTABLE) $(CPP_EXECUTABLE)
$(C_EXECUTABLE):$(C_SOURCES)
$(CC) $< $(LDFLAGS) $(CFLAGS) -o $@
$(CPP_EXECUTABLE):$(CPP_SOURCES)
$(CPP) $< $(LDFLAGS) $(CFLAGS) -o $@
clean:
rm -rf $(EXECUTABLE)
@Kareem786-sa
Copy link

how to to compile all c files in the sub directories. Please if any one knows..

@lochyj
Copy link

lochyj commented Apr 7, 2023

@Kareem786-sa
Try $(shell find . -name '*.c') or $(shell find . -name '*.cpp') instead of $(wildcard *.c)

@Akul123
Copy link

Akul123 commented Aug 19, 2023

Correct me if I am wrong but like this you will build same source file several times and object file will be named differently. I think that problem is in the lines 12 and 15 where automatic variable $< is used, $< means first from prerequisites and in this case is some .c file from CPP_SOURCES.
When command from line 12 gets unrolled then you get "gcc some_file.c -o C_EXECUTABLE", and in next iteration same file will be used as source file but target will be different.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment