Languages/C

Makefile

leohycho 2022. 5. 23. 21:00

Build :

gcc -c main.c // -c (compile)
gcc -c -o target.o main.c

~$ main.o

~$ target.o

gcc -o target main.o // -o (output)

~$ target.exe

 

option : 

gcc -v -I/usr/local/include -DDEBUG -Wall -W -O2 -L/usr/local/lib -o like like.c -lm

 

Make rules : 

target: dependencies ...
         commands
          ...

Example :

~$ gcc -c main.c
~$ gcc -c a.c
~$ gcc -c b.c
~$ gcc -o target main.o a.o b.o 

 

Example by makefile :

a.o : a.h a.c
       gcc -c a.c
b.o : b.h b.c
       gcc -c b.c
main.o : a.h b.h main.c
            gcc -c main.c
target : a.o b.o main.o
          gcc -o target a.o b.o main.o 

 

Example by makefile using macro : 

CC = g++
CXXFLAGS = -Wall -O2
LDFLAGS =

SRC_DIR = ./src
OBJ_DIR = ./obj
INC_DIR = ./include

TARGET = test

SRCS = $(notdir $(wildcard $(SRC_DIR)/*.cpp))

OBJS = $(SRCS:.cpp=.o)

OBJECTS = $(patsubst %.o,$(OBJ_DIR)/%.o,$(OBJS))
DEPS = $(OBJECTS:.o=.d)

all: $(TARGET)

$(TARGET) : $(OBJECTS)
        $(CC) $(CXXFLAGS) $(OBJECTS) -o $(TARGET) $(LDFLAGS)

$(OBJ_DIR)/%.o : $(SRC_DIR)/%.cpp
        $(CC) $(CXXFLAGS) -I$(INC_DIR) -c $< -o $@ -MD $(LDFLAGS)

.PHONY: clean
clean:
        rm -f $(OBJECTS) $(DEPS) 

 

 

Reference

[1] http://www.gnu.org/software/make/

[2] https://github.com/TheNetAdmin/Makefile-Templates