[Linux] make - 3
이젠 Makefile 을 src 에 두지 않고 아래와 같이 따로 상위 폴더로 분리 해 보자
/* include/my_math.h */
int add(int x, int y);
int subtract(int x, int y);
int multiply(int x, int y);
int divide(int x, int y);
/* src/main.c */
#include <stdio.h>
#include <pthread.h>
#include <my_math.h>
void* thread_func(void *data)
{
printf("[%s]\n", __func__);
printf("%d\n", add(10, 5));
printf("%d\n", subtract(10, 5));
printf("%d\n", multiply(10, 5));
printf("%d\n", divide(10, 5));
return 0;
}
int main(void)
{
pthread_t thread;
pthread_create(&thread, 0, thread_func, 0);
pthread_join(thread, 0);
return 0;
}
/* src/add.c */
#include <my_math.h>
int add(int x, int y)
{
return x + y;
}
//---------------------------------------------------------------------------------------------
/* src/subtract.c */
#include <my_math.h>
int subtract(int x, int y)
{
return x - y;
}
//---------------------------------------------------------------------------------------------
/* src/multiply.c */
#include <my_math.h>
int multiply(int x, int y)
{
return x * y;
}
//---------------------------------------------------------------------------------------------
/* src/divide.c */
#include <my_math.h>
#include <stdio.h>
#include <stdlib.h>
int divide(int x, int y)
{
if(y == 0) {
fprintf(stderr, "Can not divide as zero\n");
exit(1);
}
return x / y;
}
# Makefile
SRC_DIR = src
OBJ_DIR = obj
BIN_DIR = bin
EXE = $(BIN_DIR)/exe
SRC = $(wildcard $(SRC_DIR)/*.c)
OBJ = $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)
CC = gcc
CPPFLAGS = -Iinclude -MMD -MP
CFLAGS = -c -Wall
LDFLAGS = -Llib
LDLIBS = -lpthread
.PHONY: all clean
all: $(EXE)
$(EXE): $(OBJ) | $(BIN_DIR)
$(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c | $(OBJ_DIR)
$(CC) $(CPPFLAGS) $(CFLAGS) $< -o $@
$(BIN_DIR) $(OBJ_DIR):
@mkdir -p $@
clean:
@rm -rf $(BIN_DIR) $(OBJ_DIR)
echo "Clean project"
-include $(OBJ:.o=.d)
라이브러리도 만들어 추가 해 보자
# src/Makefile
SRC_DIR = src
OBJ_DIR = obj
LIB_DIR = lib
BIN_DIR = bin
EXE = $(BIN_DIR)/exe
SRC = $(wildcard $(SRC_DIR)/*.c)
OBJ = $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)
LIB = $(LIB_DIR)/lib$(MY_LIB).a
MY_LIB = my_math
CC = gcc
CPPFLAGS = -Iinclude -MMD -MP
CFLAGS = -c -Wall
LDFLAGS = -Llib
LDLIBS = -lpthread -l$(MY_LIB)
.PHONY: all clean
all: $(LIB) $(EXE)
$(EXE): $(OBJ) | $(BIN_DIR)
$(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@
$(LIB) : $(OBJ) | $(LIB_DIR)
ar rcv $@ obj/add.o obj/subtract.o obj/multiply.o obj/divide.o
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c | $(OBJ_DIR)
$(CC) $(CPPFLAGS) $(CFLAGS) $< -o $@
$(BIN_DIR) $(LIB_DIR) $(OBJ_DIR):
@mkdir -p $@
clean:
@rm -rf $(BIN_DIR) $(LIB_DIR) $(OBJ_DIR)
echo "Clean project"
-include $(OBJ:.o=.d)
make로 빌드 하면 결과는 다음과 같다.