files in the folder:
ls -l
-rw-r--r-- 1 ysgc staff 98 Aug 15 13:40 func1.cpp
-rw-r--r-- 1 ysgc staff 106 Aug 15 13:30 func2.cpp
-rw-r--r-- 1 ysgc staff 41 Aug 15 12:45 funcs.h
-rw-r--r-- 1 ysgc staff 198 Aug 15 13:48 main.cpp
// main.cpp
#include <iostream>
#include "funcs.h"
int main(){
std::cout << std::endl;
print_hello();
std::cout << std::endl;
std::cout << "The factorial of 5 is " << factorial(5) << std::endl;
return 0;
}
//funcs.h
void print_hello();
int factorial(int n);
// func1.cpp
#include "funcs.h"
int factorial(int n){
if (n != 1){
return n*factorial(n-1);
}
return 1;
}
// func2.cpp
#include <iostream>
#include "funcs.h"
void print_hello(){
std::cout << "hello world!!!" << std::endl;
}
1. Brute force
clang++ main.cpp func1.cpp func2.cpp -o hello && ./hello
hello world!!!
The factorial of 5 is 120
2. Makefile example 1
https://www.youtube.com/watch?v=aw9wHbFTnAQ
subl Makefile
注意這里M是大寫的
all:
clang++ main.cpp func1.cpp func2.cpp -o a.out
compile:
make && ./a.out
默認(rèn)make第一個(gè)內(nèi)容廷雅,這里是“all”
all:
compile:
clang++ main.cpp func1.cpp func2.cpp -o a.out
make compile && ./a.out
指定需要運(yùn)行的內(nèi)容名字厉亏,這里是“compile”
all: main.o func1.o func2.o # has these dependencies
clang++ main.o func1.o func2.o -o a.out && ./a.out
main.o: main.cpp # check if main.cpp exists or not
clang++ -c main.cpp
func1.o: func1.cpp
clang++ -c func1.cpp
func2.o: func2.cpp
clang++ -c func2.cpp
clean:
rm -rf *o a.out
# format
# target: dependency
# command
make && make clean
# define variables
CC=clang++
CFLAGS=-c -Wall
all: main.cpp func1.o func2.o # has these dependencies
$(CC) main.cpp func1.o func2.o -o a.out && ./a.out
func1.o: func1.cpp # check if func1.cpp exists or not
$(CC) $(CFLAGS) func1.cpp
func2.o: func2.cpp
$(CC) $(CFLAGS) func2.cpp
clean:
rm -rf *o a.out
# format
# target: dependency
# command
make && make clean
3. Makefile example 2
https://www.youtube.com/watch?v=_r7i5X0rXJk
// main.cpp
#include <cstdlib>
#include "message.h"
using namespace std;
int main(){
message m;
m.printMessage();
return 0;
}
//message.h
#ifndef MESSAGE_H
#define MESSAGE_H
class message{
public:
void printMessage();
};
#endif
//message.cpp
#include <iostream>
#include "message.h"
using namespace std;
void message::printMessage(){
cout << "Makefile example\n";
}
#Makefile
all: main.cpp message.o
clang++ main.cpp message.o -o a.out && ./a.out
message.o: message.cpp
clang++ -c message.cpp
clean:
rm -rf *o a.out
4. Example 3
https://www.youtube.com/watch?v=j02hcX7R1yI
- directly output an executable file
-
-o a.out
,-o exe_file
-
- two steps:
- link file:
-c file1.cpp
or-c file1.cpp -o file1.o
- to exe:
xxx.o yyy.o zzz.o -o exe_file
- link file: