Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make recursive all C files

Tags:

c

makefile

I really can't get into makefiles. In previous projects, I hardcoded all compile tasks in the Makefile:

all: compile_a compile_b compile_c

compile_a:
    ${CC} ${CFLAGS} ${A_SRC} -o ${A_OUT}

and so on.

But as the latest project has more files than every project before, I want to write better make tasks and of course LESS characters as make is not really friendly to my eyes (it makes them suffer)! :-P

What I want:

  • One task to rule them all (just make projectname or make all, you know?)
  • One task for every C file to compile (I read something about this %.o: %.c syntax, but didn't really get it)
  • One task for linking (how to get all .o files and link them without hardcoding each?)
  • One task for cleaning (oh, i can do this!)

The project structure is:

bin (binary goes here!)
src
  some
  directories 
  are
  here

I don't know if I need a directory for object files, I put them in ./bin, I think that's good enough, isn't it?

Maybe I just need someone who can explain it with easy words!

EDIT: As someone pointed out, there's no real question, so here it goes:

  • how to recursively compile all C files to bin/(filename).o
  • how to link all .o files in 'bin/' without knowing their names

maybe this helps.

like image 687
musicmatze Avatar asked Jan 29 '13 18:01

musicmatze


1 Answers

I frequently use the wildcard function in combination with the foreach function for something like you want to achieve.

If your sources are in src/ and you want to put the binaries into bin/ the basic construction of my Makefile would look like follows:

SOURCES=$(shell find src -type f -iname '*.c')

OBJECTS=$(foreach x, $(basename $(SOURCES)), $(x).o)

TARGET=bin/MyProject

$(TARGET): $(OBJECTS)
    $(CC) $^ -o $@

clean:
    rm -f $(TARGET) $(OBJECTS)

I usually take advantage of make's built in implicit rules and predefined variables (Make manual, Chap 10).

like image 178
user1146332 Avatar answered Sep 19 '22 05:09

user1146332