four files
main.cpp
#include
#include "functions.h"
using namespace std;
int main()
{
printhello();
cout << "This is main:" << endl;
cout << "The factorial of 5 is: " << factorial(5) << endl;
return 0;
}
factorial.cpp
#include "functions.h"
int factorial(int n)
{
if (n == 1)
return 1;
else
return n * factorial(n - 1);
}
printhello.cpp
#include
#include "functions.h"
using namespace std;
void printhello()
{
int i;
cout << "Hello World!" << endl;
}
functions.h
#ifndef _FUNCTIONS_H_
#define _FUNCTIONS_H_
void printhello();
int factorial(int n);
#endif
g++ main.cpp factorial.cpp printhello.cpp -o main
如果有很多文件?
是否需要每次都要在命令行编译?
Makefile is a tool to simplify and organize compilation. Makefile is a set of commands with variable names and targets . You can compile your project(program) or only compile the update files in the project by using Makefile.
The name of makefile must be either makefile or Makefile without extension. You can write makefile in any text editor. A rule of makefile including three elements: targets, prerequisites and commands. There are many rules in the makefile.
• The target is an object file, which is generated by a program. Typically, there is only one per rule.
• The prerequisites are file names, separated by spaces, as input to create the target.
• The commands are a series of steps that make carries out. These need to start with a tab character, not spaces.
Makefile
Makefile
# ## VERSION 1
hello: main.cpp printhello.cpp factorial.cpp
g++ -o hello main.cpp printhello.cpp factorial.cpp
在命令窗口输入:
make
编译并声称hello执行文件
运行hello:
./hello
Makefile
# ## VERSION 2
CXX = g++
TARGET = hello
OBJ = main.o printhello.o factorial.o
$(TARGET): $(OBJ)
$(CXX) -o $(TARGET) $(OBJ)
main.o: main.cpp
$(CXX) -c main.cpp
printhello.o: printhello.cpp
$(CXX) -c printhello.cpp
factorial.o: factorial.cpp
$(CXX) -c factorial.cpp
在命令窗口输入:
make
分别编译main.cpp, printhello.cpp, factorial.cpp, 并将其链接生成hello
./hello
Makefile
# ## VERSION 3
CXX = g++
TARGET = hello
OBJ = main.o printhello.o factorial.o
CXXFLAGS = -c -Wall
$(TARGET): $(OBJ)
$(CXX) -o $@ $^
%.o: %.cpp
$(CXX) $(CXXFLAGS) $< -o $@
.PHONY: clean
clean:
rm -f *.o $(TARGET)
更加的模块化一点,不用一个一个编译命令都写出来
命令窗口输入:
make
分别编译main.cpp, printhello.cpp, factorial.cpp, 并生成相应的.o文件,并将其链接生成hello。
make clean
删掉所有的.o 和 目标文件
Makefile
## VERSION 4
CXX = g++
TARGET = hello
SRC = $(wildcard *.cpp)
OBJ = $(patsubst %.cpp, %.o, $(SRC))
CXXFLAGS = -c -Wall
$(TARGET): $(OBJ)
$(CXX) -o $@ $^
%.o: %.cpp
$(CXX) $(CXXFLAGS) $< -o $@
.PHONY: clean
clean:
rm -f *.o $(TARGET)
make
分别编译main.cpp, printhello.cpp, factorial.cpp, 并生成相应的.o文件,并将其链接生成hello。
./hello
make clean
删掉所有的.o文件和hello