I've just learn something about makefile and here is my first question for it.I have main.cpp hello.cpp factorial.cpp and functions.h files
all: hello
hello: main.o factorial.o hello.o
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
Run Code Online (Sandbox Code Playgroud)
In the code above, why files have an extention .o ? shouldnt be .cpp or what is the differences between using .cpp and .o
Building a C++ program is a two-stage process. First, you compile each .cpp file into a .o object file. Compiling converts the source code into machine code but doesn't resolve function calls from other source files (since they haven't been compiled yet).
main.o: main.cpp
g++ -c main.cpp
factorial.o: factorial.cpp
g++ -c factorial.cpp
hello.o: hello.cpp
g++ -c hello.cpp
Run Code Online (Sandbox Code Playgroud)
Second, you link the object files together to create an executable. Linking resolves the external references in each object file.
hello: main.o factorial.o hello.o
g++ main.o factorial.o hello.o -o hello
Run Code Online (Sandbox Code Playgroud)
By the way, there is a typo in the clean target. *o should be *.o.
clean:
rm -rf *.o hello
Run Code Online (Sandbox Code Playgroud)