주로 컴파일관련한 행동을 한다.
컴파일 해야할 코드 갯수가 많아지면 gcc 방식으로 하나하나 입력하는 것은 매우 번거로운 일이다. 따라서 이러한 불편함을 해결하고 쉽게 컴파일하기 위해 사용하기 위한 방법이 make이다.
make
make 명령어를 친 폴더에 있는 Makefile을 찾고 그 Makefile에 쓰여 있는 대로 동작함.
/* main.c */
#include <stdio.h>
#include "sum.h"
int main(){
printf("hello\n");
printf("s = %d\n",sum(10,23));
return 1;
}
/* sum.h */
#ifndef __SUM_H__
#define __SUM_H__
int sum(int a,int b);
#endif
/* sum.c */
#include "sum.h"
int sum(int a,int b){
return a + b;
};
CC = gcc
target1 : dependency1 dependency2
command1
command2
target2 : dependency3 dependency4
command3
command4
/* Makefile */
test : main.o sum.o
gcc -o test main.o sum.o
main.o : main.c
gcc -c main.c
sum.o : sum.c
gcc -c sum.c
clean :
rm *.o test
target : dependency
target 뒤에 dependency에 아무것도 없는것은 기본적으로 실행되지 않는다
따라서 make clean 이런 식으로 따로 실행시켜주는 것이다.
$ make clean
rm *.o test
먼저 이미 만들어진 오브젝트파일과 실행파일 test를 삭제해 줌
$ make
gcc -c main.c
gcc -c sum.c
gcc -o test main.o sum.o
make를 실행하면 컴파일이 된다
$ ./test
hello
s = 33
그리고 실행해보면 잘 실행이 된다
CC=gcc
EXE=test
$(EXE) : main.o sum.o
$(CC) -o main.o sum.o
main.o : main.c
$(CC) -c -o main.o main.c
sum.o : sum.c
$(CC) -c -o sum.o sum.c
clean :
rm *.o test
CROSS=
CC=$(CROSS)gcc
EXE=test
OBJS=main.o sum.o
all : $(EXE)
$(EXE) : $(OBJS)
$(CC) -o $@ $^
clean :
rm *.o test
CROSS=arm-
CC=$(CROSS)gcc
이런식으로 크로스컴파일을 사용함
arm- , mips-linux-, .....
CROSS=
CC=$(CROSS)gcc
EXE=test
OBJS=main.o sum.o
CFLAGS=-I./include //CFLAGS 이름 바꾸면 실행 안됨.
//헤더파일들이 include 폴더에 있다는 것을 알려줌
all : $(EXE)
$(EXE) : $(OBJS)
$(CC) $(CFLAGS) -o $@ $^
clean :
rm *.o test
실습파일 수정
/* main.c */
#include <stdio.h>
#include "sum.h"
int main(){
#ifdef DEBUG
printf("DEBUG\n");
printf("s = %d\n",sum(10,23));
#else
printf("hello\n");
printf("s = %d\n",sum(1,3));
return 1;
#endif
}
/* Makefile */
CROSS=
CC=$(CROSS)gcc
EXE=test
OBJS=main.o sum.o
DEFINES=-DDEBUG //DEBUG를 정의했을 때
CFLAGS=-I./include $(DEFINES)
all : $(EXE)
$(EXE) : $(OBJS)
$(CC) $(CFLAGS) -o $@ $^
clean :
rm *.o test
실행결과

CROSS=
CC=$(CROSS)gcc
EXE=test
OBJS=main.o sum.o
DEFINES=-DDEBUG
CFLAGS=-I./include $(DEFINES)
LDFLAGS=-lpthread
all : $(EXE)
$(EXE) : $(OBJS)
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
clean :
rm *.o test
CROSS=
CC=$(CROSS)gcc
EXE=test
DEFINES=-DDEBUG
CFLAGS=-I./include $(DEFINES)
LDFLAGS=-lpthread
// OBJS=main.o sum.o
// *.c 파일들 전부가 C_SRC에 들어감
C_SRC = $(wildcard *.c)
OBJS = $(C_SRC:.c=.o) // *.c -> *.o 바꿔라
all : $(EXE)
$(EXE) : $(OBJS)
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
clean :
rm *.o test
소스파일들을 하나씩 전부 OBJS에 쓰기 힘드니까
wildcard가 소스파일을 알아서 넣어준다.
CROSS= /* 크로스컴파일 필요하면 넣기*/
CC=$(CROSS)gcc
EXE=test
C_SRC = $(wildcard *.c)
OBJS = $(C_SRC:.c=.o)
DEFINES=-DDEBUG
CFLAGS=-I./include $(DEFINES)
LDFLAGS=-lpthread /*라이브러리 탑재*/
all : $(EXE)
$(EXE) : $(OBJS)
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
clean :
rm *.o test