caesar
caesar

Reputation: 3135

using .o files in makefile

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

In the code above, why files have an extention .o ? shouldnt be .cpp or what is the differences between using .cpp and .o

Upvotes: 1

Views: 9839

Answers (2)

John Kugelman
John Kugelman

Reputation: 362087

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

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

By the way, there is a typo in the clean target. *o should be *.o.

clean:
    rm -rf *.o hello

Upvotes: 5

bash.d
bash.d

Reputation: 13217

.o denote "object-files", these are files compiled from source but not yet linked into an executable or a library.
In your make-file, i.e.

main.o : main.cpp

says that main.o will be created from main.cpp using g++ -c main.cpp.

Eventually, all files with .o will create the executable hello as stated in

hello: main.o factorial.o hello.o
     g++ main.o factorial.o hello.o -o hello

Upvotes: 2

Related Questions