2.2.10. Example: Building a C++ program with the GCC (compiling and linking in two steps)
To build a minimal C++ program by using a two-step process, first compile the source into an object file, and then link it to create the executable. This approach demonstrates modular building with the GNU Compiler Collection (GCC) compiler.
Procedure
Create a directory
hello-cpp:$ mkdir hello-cppChange to the created directory:
$ cd hello-cppCreate file
hello.cppwith the following contents:#include <iostream> int main() { std::cout << "Hello, World!\n"; return 0; }Compile the code with
g++:$ g++ -c hello.cppThe object file
hello.ois created.Link an executable file
helloworldfrom the object file:$ g++ hello.o -o helloworldRun the resulting executable file:
$ ./helloworldHello, World!Optional: Change back to the parent directory:
$ cd ..Optional: Remove the
hello-cppdirectory:$ rm -r hello-cpp