How to Compile a C++ Program Using GCC

Mohd Mohtashim Nawaz Feb 02, 2024
  1. Use gcc to Compile a C++ Program
  2. Use g++ vs gcc to Compile a C++ Program
  3. Conclusion
How to Compile a C++ Program Using GCC

Both gcc and g++ are GNU project compilers that you can use to compile a C++ program. This article discusses how to compile a C++ program using gcc.

Use gcc to Compile a C++ Program

As the manual page of gcc says, the compiler can compile the C++ programs together with the C programs.

However, running the usual gcc command from the terminal (or any other command-line program) shows an error.

The error is not generated because of the compiling issues; rather, the linker generates the error. This is because gcc links the programs to the C language by default.

To change the linker behavior of gcc, you can pass the extra argument containing the name of the linker that links to C++. Let us see the command line code to do so.

gcc myProgram.cpp -lstdc++

It will generate an object file names a.out. You can use the -o flag to name your object file.

gcc myProgram.cpp -lstdc++ -o myProgram

You need to execute the myProgram file to run the program. You can do so by running the following command on a Linux terminal.

./myProgram

Note that for C++ programs, you must provide a C++ extension to your program file. The C++ extensions are given below.

  1. .cpp
  2. .cc
  3. .C (note the case of the letter)

Use g++ vs gcc to Compile a C++ Program

Although you can compile your C++ code with gcc, it makes the process much more complicated as you have to pass the extra argument each time.

Therefore, it is much better to use the g++ compiler for compiling C++ programs. It automatically links the code to C++ linker without any extra arguments.

You can compile the code using g++ as given below.

g++ myProgram.cc

It produces the object file named a.out. You can use the -o flag below to name your object file.

g++ myProgram.cc -o myProgram

You can run the program the same way as in the previous section.

Conclusion

It is advisable not to use gcc to compile C++ programs until necessary to avoid unwanted errors. It is also more likely to cause portability issues.

Hope you have enjoyed reading the article. Stay tuned for such articles.

Related Article - C++ GCC