0
Compiling C++ codes by GCC
Posted by Derek Jing
on
12:36 PM
in
C++
Compiling a single C++ program
Suppose we have a C++ source code 'hello.cpp', then we can use following command to compile it:
$g++ -Wall -c hello.cpp
Then we can link the object file
$g++ hello.o -o hello.out
Alternatively, above two steps can be combined together as following
$ g++ -Wall hello.cpp -o hello.out
where an executable hello.out is output directly without generating intermediate object file hello.o.
Compiling multiple C++ codes simultaneously
Suppose we have three C++ codes
Then we can compile the two CPP files simultaneously
$g++ -Wall main.cpp myclass.cpp -o myrun.out
Compiling multiple C++ codes independently
The benefit is independent compilation is that if one CPP file is edited, we just need to compile this file, saving time for compiling all other CPP files.
$g++ -Wall -c myclass.cpp ==> generate myclass.o
$g++ -Wall -c main.cpp ==> generate main.o
$g++ main.o myclass.o -o myrun ==> generate executable myrun.out
Suppose we have a C++ source code 'hello.cpp', then we can use following command to compile it:
$g++ -Wall -c hello.cpp
This command compiles hello.cpp and outouts an object file hello.o. The option -Wall displays complier warnings.
$g++ hello.o -o hello.out
This command links the object file hello.o into an executable file hello.out; It is not necessary to use .out as the extension for the executable file. It is also ok to give an executable filename without extension; If the option '-o filename' is omitted, then the output executable will be a.out.
$ g++ -Wall hello.cpp -o hello.out
where an executable hello.out is output directly without generating intermediate object file hello.o.
Suppose we have three C++ codes
myclass.h: a header file, including the class interface; myclass.cpp: the class implementation file, having #include "myclass.h"; main.cpp: the main file using the class, having #include "myclass.h"
$g++ -Wall main.cpp myclass.cpp -o myrun.out
The benefit is independent compilation is that if one CPP file is edited, we just need to compile this file, saving time for compiling all other CPP files.
$g++ -Wall -c myclass.cpp ==> generate myclass.o
$g++ main.o myclass.o -o myrun ==> generate executable myrun.out
Post a Comment