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

  1. Create a directory hello-cpp:

    $ mkdir hello-cpp
  2. Change to the created directory:

    $ cd hello-cpp
  3. Create file hello.cpp with the following contents:

    #include <iostream>
    
    int main() {
      std::cout << "Hello, World!\n";
      return 0;
    }
  4. Compile the code with g++:

    $ g++ -c hello.cpp

    The object file hello.o is created.

  5. Link an executable file helloworld from the object file:

    $ g++ hello.o -o helloworld
  6. Run the resulting executable file:

    $ ./helloworld
    Hello, World!
  7. Optional: Change back to the parent directory:

    $ cd ..
  8. Optional: Remove the hello-cpp directory:

    $ rm -r hello-cpp
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

关于红帽文档

Legal Notice

Theme

© 2026 Red Hat
返回顶部