Skip to content

Instantly share code, notes, and snippets.

@rohanorton
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohanorton/2a888f2295bc3be24d79 to your computer and use it in GitHub Desktop.
Save rohanorton/2a888f2295bc3be24d79 to your computer and use it in GitHub Desktop.
######
# This Makefile was written to compile my attempts while studying Learn C the Hard Way
# it will look inside the src directory and compile all files ending in .c to the bin directory,
# one executable for every source file (no linking, no object files etc.)
######
## Debug CFLAGS:
CFLAGS=-Wall -g -pipe
## Non-debug CFLAGS:
#CFLAGS=-pipe -O2
CC=gcc
## alternatively:
#CC=clang
## don't even know why i'm doing this...:
RM=rm -f
## Keep source files in src/ dir:
SOURCE_DIR=./src/
## Compile programs to bin/ dir:
PROGRAM_DIR=./bin/
## list of all .c files in src/ dir:
SOURCE_FILES = $(wildcard $(SOURCE_DIR)*.c)
## source files with .c removed and directory changed to bin/:
PROGRAM_FILES = $(patsubst %.c,%,$(patsubst $(SOURCE_DIR)%,$(PROGRAM_DIR)%,$(SOURCE_FILES)))
## Use .PHONY to prevent make from attempting to use target as a file target
.PHONY: all
## Use our list of programs as dependencies...
all: $(PROGRAM_FILES)
## each of the dependencies for all will have to be compiled
## so we can provide rules for compilation with this target:
$(PROGRAM_DIR)%: $(SOURCE_DIR)%.c
## essentially ./bin/example: ./src/example.c
## which runs the following compilation code:
$(CC) $(CFLAGS) $< -o $@
## $< is first dependency (./src/example.c)
## $@ is target (./bin/example)
## so, gcc -Wall -g -pipe ./src/example.c -i ./bin/example
## Finally, lets have a command to remove all the compiled binaries
.PHONY: clean
clean:
$(RM) $(PROGRAM_FILES)
@rohanorton
Copy link
Author

.PHONY informs make that this target is in fact a user defined command and prevents make from interpreting it as a file target. This is important because we might have a file in our directory with the same name as the command, and in this scenario make would see that a file exists that the target appears to be referring to and as a result would not execute the user defined command (see http://stackoverflow.com/a/2145605/2800005)

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