Search code examples
c++g++

Difference between compiling with object and source files


I have a file main.cpp containing an implementation of int main() and a library foo split up between foo.h and foo.cpp.

What is the difference (if any) between

g++ main.cpp foo.cpp -o main

and

g++ -c foo.cpp -o foo.o && g++ main.cpp foo.o

?

Edit: of course there is a third version:

g++ -c foo.cpp -o foo.o && g++ -c main.cpp -o main.o && g++ main.o foo.o -o main

Solution

  • If you type something like this:

    g++ -o main main.cpp foo.cpp 
    

    You are compiling and linking two cpp files at once and generating an executable file called main (you get it with -o)

    If you type this:

    g++ main.cpp foo.cpp
    

    You are compiling and linking two cpp files at once, generating an executable file with the default name a.out.

    Finally, if you type this:

    g++ -c foo.cpp
    

    You will generate an object file called foo.o which can later be linked with g++ -o executable_name file1.o ... fileN.o

    Using options -c and -o allows you to perform separately two of the tasks performed by the g++ compiler and getting the corresponding preprocessed and object files respectively. I have found a link which may provide you helpful information about it. It talks about gcc (C compiler), but both g++ and gcc work similarly after all:

    http://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html

    Be careful with the syntax of the commands you are using. If you work with Linux and you have problems with commands, just open a cmd window and type "man name_of_the_command", in order to read about, syntax, options, return values and some more relevant information about commands, system calls, user library functions and many other issues.

    Hope it helps!