# Makefile

​​

![makefile flowchart](/files/TRSUOjlNwlQB1NDBXGsE)

### ตัวอย่างไฟล์ Makefile อย่างง่ายแบบที่ 1

![](/files/Kx9xs3cVNmVzPmGu3qct)

<pre class="language-c"><code class="lang-c">all: hello

<strong>hello:	main.o factorial.o hello.o
</strong>	g++ main.o factorial.o hello.o -o hello
main.o:	main.cpp
	g++ -c main.cpp
factorial.o:	factorial.cpp
	g++ -c factorial.cpp
hello.o:	hello.cpp
	g++ -c hello.cpp
clean:
	rm -rf *o hello
</code></pre>

### ตัวอย่างไฟล์ Makefile อย่างง่ายแบบที่ 2

ใช้ macro เพื่อสร้างตัวแปร CC และ CFLAGS

```c
# the compiler to use
CC=g++
# options passed to the compiler
CFLAGS=-c -Wall

all:	hello

hello:	main.o factorial.o hello.o
	$(CC) main.o factorial.o hello.o -o hello
main.o:	main.cpp
	$(CC) $(CFLAGS) main.cpp
factorial.o:	factorial.cpp
	$(CC) $(CFLAGS) factorial.cpp
hello.o:	hello.cpp
	$(CC) $(CFLAGS) hello.cpp
clean:
	rm -rf *o hello
```

### ตัวอย่างไฟล์ Makefile อย่างง่ายแบบที่ 3

สร้างตัวแปร SOURCES, OBJECTS และ EXECUTABLE เพื่อรวมไฟล์โปรแกรมเข้าด้วยกัน

```c
CC=g++
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=main.cpp hello.cpp factorial.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=hello

all:	$(SOURCES) $(EXECUTABLE)
	
$(EXECUTABLE): $(OBJECTS) 
	$(CC) $(LDFLAGS) $(OBJECTS) -o $@
.cpp.o:
	$(CC) $(CFLAGS) $< -o $@
clean:
	rm -rf $(OBJECTS) $(EXECUTABLE)
```

### ตัวอย่างไฟล์ Makefile อย่างง่ายแบบที่ 4

ในกรณีที่มีการอ้างอิง (include) ไฟล์ header (.h) เพิ่มหรือไลบรารีภายนอกเพิ่มเติม จะต้องใส่ option -I และ -l เพิ่มเข้าไป

```c
CC=g++
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=main.cpp hello.cpp factorial.cpp
OBJECTS=$(SOURCES:.cpp=.o)
MY_INCLUDES=/home/student/project/myLib/
MY_LIBRARIES=zlib fltk
EXECUTABLE=hello

all:	$(SOURCES) $(EXECUTABLE)
	
$(EXECUTABLE):	$(OBJECTS) 
	$(CC) -I$(MY_INCLUDES) $(LDFLAGS) $(OBJECTS) -o $@ -l$(MY_LIBRARIES)
@echo "Compile hello completed..." 
.cpp.o:
	$(CC) $(CFLAGS) $< -o $@
@echo "Compile all object files completed..."
clean:
	rm -rf $(OBJECTS) $(EXECUTABLE)
@echo "Clean all object files and hello program done..."
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aic-eec.com/c-c++-for-embedded-programming/principle-c-c++-programming/makefile.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
