คำอธิบาย
Makefile คือไฟล์สคริปต์สำหรับอัตโนมัติการคอมไพล์โปรเจกต์ C++ ขนาดใหญ่ แยก source code เป็นหลายไฟล์ (.cpp, .h) แล้ว link รวมกัน
โครงสร้างตัวอย่าง
project/ ├── Makefile ├── main.cpp ├── functions.h ├── multiply.cpp ├── factorial.cpp └── print.cpp
Makefile
CC = g++ CFLAGS = -Wall -std=c++11 OBJ = main.o multiply.o factorial.o print.o all: program program: $(OBJ) $(CC) $(CFLAGS) -o program $(OBJ) main.o: main.cpp functions.h $(CC) $(CFLAGS) -c main.cpp multiply.o: multiply.cpp functions.h $(CC) $(CFLAGS) -c multiply.cpp factorial.o: factorial.cpp functions.h $(CC) $(CFLAGS) -c factorial.cpp print.o: print.cpp functions.h $(CC) $(CFLAGS) -c print.cpp clean: rm -f *.o program
Source Files
functions.h
#ifndef FUNCTIONS_H #define FUNCTIONS_H void print(); int factorial(int); int multiply(int, int); #endif
multiply.cpp
#include "functions.h"
int multiply(int a, int b) { return a * b; }
factorial.cpp
#include "functions.h"
int factorial(int n) {
if(n <= 1) return 1;
return n * factorial(n - 1);
}
print.cpp
#include <iostream>
#include "functions.h"
using namespace std;
void print() { cout << "makefile" << endl; }
main.cpp
#include <iostream>
#include "functions.h"
using namespace std;
int main() {
cout << multiply(1, 2) << endl;
cout << factorial(5) << endl;
print();
return 0;
}
การใช้งาน
$ make g++ -Wall -std=c++11 -c main.cpp g++ -Wall -std=c++11 -c multiply.cpp g++ -Wall -std=c++11 -c factorial.cpp g++ -Wall -std=c++11 -c print.cpp g++ -Wall -std=c++11 -o program main.o multiply.o factorial.o print.o $ ./program 2 120 makefile