- How To Compile And Run a C/C++ Code In Linux
- Step #1: Install C/C++ compiler and related tools
- Step #2: Verify installation
- How to Compile and Run C/C++ program on Linux
- How do I compile the program on Linux?
- How do I run or execute the program called demo on Linux?
- Compiling and running a simple C++ program
- How do I generate symbolic information for gdb and warning messages?
- How do I generate optimized code on a Linux machine?
- How do I compile a C program that uses math functions?
- How do I compile a C++ program that uses Xlib graphics functions?
- How do I compile a program with multiple source files?
- Installing GCC
- Building GCC
- Support libraries
- Configuration
- Compile C Program in Linux Using GCC
- Installing GCC on Ubuntu and Debian GNU/Linux:
- Installing GCC on Linux Mint:
- Installing GCC on CentOS 7 and Fedora:
- Installing GCC on Arch Linux:
- Writing Your First C Program:
- Compiling and Running C Programs with GCC:
How To Compile And Run a C/C++ Code In Linux
I am a new Linux user and student who used to write C or C++ programs on MS-Windows. Now, I am using Ubuntu Linux. How can I compile a C or C++ program on Linux operating systems using bash Terminal application?
To compile a C or C++ program on any Linux distro such as Ubuntu, Red Hat, Fedora, Debian and other Linux distro you need to install:
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | GNU C/C++ compiler |
Est. reading time | 2 minutes |
- GNU C and C++ compiler collection
- Development tools
- Development libraries
- IDE or text editor to write programs
Step #1: Install C/C++ compiler and related tools
If you are using Fedora, Red Hat, CentOS, or Scientific Linux, use the following yum command to install GNU c/c++ compiler:
# yum groupinstall ‘Development Tools’
If you are using Debian or Ubuntu Linux, type the following apt-get command to install GNU c/c++ compiler:
$ sudo apt-get update
$ sudo apt-get install build-essential manpages-dev
Step #2: Verify installation
Type the following command to display the version number and location of the compiler on Linux:
$ whereis gcc
$ which gcc
$ gcc —version
Sample outputs:
Fig. 01: GNU C/C++ compilers on Linux
How to Compile and Run C/C++ program on Linux
Create a file called demo.c using a text editor such as vi, emacs or joe:
How do I compile the program on Linux?
Use any one of the following syntax to compile the program called demo.c:
In this example, compile demo.c, enter:
If there is no error in your code or C program then the compiler will successfully create an executable file called demo in the current directory, otherwise you need fix the code. To verify this, type:
$ ls -l demo*
How do I run or execute the program called demo on Linux?
Simply type the the program name:
$ ./demo
OR
$ /path/to/demo
Samples session:
Animated gif 01: Compile and run C and C++ program demo
Compiling and running a simple C++ program
Create a program called demo2.C as follows:
To compile this program, enter:
To run this program, type:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
How do I generate symbolic information for gdb and warning messages?
The syntax is as follows C compiler:
cc -g -Wall input.c -o executable
The syntax is as follows C++ compiler:
g++ -g -Wall input.C -o executable
How do I generate optimized code on a Linux machine?
The syntax is as follows C compiler:
cc -O input.c -o executable
The syntax is as follows C++ compiler:
g++ -O -Wall input.C -o executable
How do I compile a C program that uses math functions?
The syntax is as follows when need pass the -lm option with gcc to link with the math libraries:
cc myth1.c -o executable -lm
How do I compile a C++ program that uses Xlib graphics functions?
The syntax is as follows when need pass the -lX11 option with gcc to link with the Xlib libraries:
g++ fireworks.C -o executable -lX11
How do I compile a program with multiple source files?
The syntax is as follows if the source code is in several files (such as light.c, sky.c, fireworks.c):
cc light.c sky.c fireworks.c -o executable
C++ syntax is as follows if the source code is in several files:
g++ ac.C bc.C file3.C -o my-program-name
See gcc(1) Linux and Unix man page for more information.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
thank you so much ur solution gave a relief…
it made my gcc command to work
Very nice article…..
In Fig. 01, you did “whereis” twice. Shouldn’t it be “which” the second time? Thanks for the tut though. Big fan!
Another mistake, please change the following comment:
## assuming that executable-file-name.c exists ##
to
## assuming that program-source-code.c exists in the current directory ##
how to compile a program that use math functions and other things?
For the sake of supplying an example, let’s say you want to use the cosine function. This is supplied in the Linux math library. The cosine function is called ‘cos()’. Similarly, the sine function is called ‘sin()’.
First, to find information about how to use them, type “man cos” in a terminal session. This gives you the manual page for the cosine function. The output from ‘man’ may vary for your system, but it likely tells you three things: 1. first, include the math.h header, 2. cos() takes a ‘double’ as its argument and it returns a double as its output, 3. to build your program, tell the C compiler to include the math library (-lm).
Here’s a sample program that does all of this:
Love it!
Thank you. I have a trouble in doing step 1 and 2. But they are fixed.
thank u ,
need pdf of the commands guide to access the c/c++/java.
to compile and run a c++ program in ubuntu follow these simple steps:
1 open terminal window.
2 type “gedit” .
3 A gedit window will appear whereyou can write your program.
4 save your program as “filename.cpp” on desktop, “.cpp” is compulsory.
5 open terminal again and type “cd Desktop”.
6 In second line type “g++ filename.cpp”.
7 Type “./a.out”.
NOW YOUR WILL RUN.
very nice to your step.
thanks
Thanks! This article really helped me to find the GNU compiler in a Linux Operating System and showed me how to compile a C program.
dear sir,
what is the procedure to run .cpp program in linux distro debian 5 ?
just about to get around to learning c along with teaching my sons it. i had no idea where to start, the first page i checked is a bumper bonanza.
Источник
Installing GCC
This page is intended to offer guidance to avoid some common problems when installing GCC, the official installation docs are in the Installing GCC section of the main GCC documentation. N.B. those installation docs refer to the development trunk, the installation instructions for released versions are included in the release sources.
For most people the easiest way to install GCC is to install a package made for your operating system. The GCC project does not provide pre-built binaries of GCC, only source code, but all GNU/Linux distributions include packages for GCC. The BSD-based systems include GCC in their ports collections. For other operating systems the Installing GCC: Binaries page lists some third-party sources of GCC binaries.
If you cannot find suitable binaries for your system, or you need a newer version than is available, you will need to build GCC from source in order to install it.
Building GCC
Many people rush into trying to build GCC without reading the installation docs properly and make one or more of these common mistakes:
do not run ./configure from within the source directory, this is not supported. You need to run configure from outside the source directory, in a separate directory created for the build (this is a FAQ)
if GCC links dynamically to the GMP, MPFR or MPC support libraries then the relevant shared libraries must be in the dynamic linker’s path, both when building gcc and when using the installed compiler (this is also a FAQ)
Support libraries
See Installing GCC: Prequisites for the software required to build GCC. If you do not have the GMP, MPFR and MPC support libraries already installed as part of your operating system then there are two simple ways to proceed, and one difficult, error-prone way. For some reason most people choose the difficult way. The easy ways are:
If it provides sufficiently recent versions, use your OS package management system to install the support libraries in standard system locations. For Debian-based systems, including Ubuntu, you should install the packages libgmp-dev, libmpfr-dev and libmpc-dev. For RPM-based systems, including Fedora and SUSE, you should install gmp-devel, mpfr-devel and libmpc-devel (or mpc-devel on SUSE) packages. The packages will install the libraries and headers in standard system directories so they can be found automatically when building GCC.
Alternatively, after extracting the GCC source archive, simply run the ./contrib/download_prerequisites script in the GCC source directory. That will download the support libraries and create symlinks, causing them to be built automatically as part of the GCC build process. Set GRAPHITE_LOOP_OPT=no in the script if you want to build GCC without ISL, which is only needed for the optional Graphite loop optimizations.
The difficult way, which is not recommended, is to download the sources for GMP, MPFR and MPC, then configure and install each of them in non-standard locations, then configure GCC with —with-gmp=/some/silly/path/gmp —with-mpfr=/some/silly/path/mpfr —with-mpc=/some/silly/path/mpc, then be forced to set LD_LIBRARY_PATH=/some/silly/path/gmp:/some/silly/path/mpfr:/some/silly/path/mpc/lib in your environment forever. This is silly and causes major problems for anyone who doesn’t understand how dynamic linkers find libraries at runtime. Do not do this. If building GCC fails when using any of the —with-gmp or —with-mpfr or —with-mpc options then you probably shouldn’t be using them.
Configuration
See Installing GCC: Configuration for the full documentation. A major benefit of running srcdir /configure from outside the source directory (instead of running ./configure) is that the source directory will not be modified in any way, so if your build fails or you want to re-configure and build again, you simply delete everything in the objdir and start again.
For example, configuring and building GCC 4.6.2 (with support for C, C++, Fortran and Go) should be as simple as:
The make step takes a long time. If your computer has multiple processors or cores you can speed it up by building in parallel using make -j 2 (or a higher number for more parallelism).
If your build fails and your configure command has lots of complicated options you should try removing options and keep it simple. Do not add lots of configure options you don’t understand, they might be the reason your build fails.
None: InstallingGCC (последним исправлял пользователь JonathanWakely 2017-07-20 19:47:08)
Источник
Compile C Program in Linux Using GCC
In this article, I will show you how to install GCC and compile C programs in Linux using GCC. I will use Debian 9 Stretch for the demonstration. But I will show you how to install GCC on wide variety of Linux distributions. Let’s get started.
Installing GCC on Ubuntu and Debian GNU/Linux:
On Ubuntu and Debian GNU/Linux distributions, GCC is really easy to install as all the required packages are available in the official package repository of Ubuntu and Debian. There is a meta package called build-essential, which installs everything you need in order to compile C and C++ programs on Ubuntu and Debian GNU/Linux distribution.
First, update the APT package repository cache with the following command:
The APT package repository cache should be updated.
Now install build-essential with the following command:
Now press y and then press to continue.
GCC should be installed.
Now you can check whether GCC is working with the following command:
Installing GCC on Linux Mint:
You can install GCC on Linux Mint the same way as in Ubuntu/Debian as shown in the earlier section of this article.
Installing GCC on CentOS 7 and Fedora:
On CentOS 7 and Fedora, GCC is easier to install as well. The required packages are available in the official package repository of CentOS 7 and Fedora. You can install the Development Tools group to install all the required packages to compile C and C++ programs on CentOS 7 and Fedora.
First, update the YUM database with the following command:
YUM database should be updated.
Now install Development Tools group packages with the following command:
Now press y and then press to continue.
If you see this message, just press y and then press .
GCC should be installed.
Now you can check whether GCC is working with the following command:
Installing GCC on Arch Linux:
You can install GCC on Arch Linux too. All the required packages are available in the Arch package repository. Arch also has a meta package base-devel, which you can install to get all the required tools needed to compile C and C++ programs on Arch Linux.
First, update the Pacman database with the following command:
Pacman database should be updated. In my case, it was already up to date.
Now install base-devel package with the following command:
Now press to select all unless you want to install very specific set of packages.
You may see something like this. It’s nothing serious as far as I know. It’s just a package was renamed from pkg-config to pkgconf. So Pacman is asking you whether you want to use the new package and remove the old one. Just press y and then press .
Now press y and then press .
GCC should be installed.
Now check whether GCC is working with the following command:
Writing Your First C Program:
Now let’s write a very simple C program, which we will compile in the next section of this article below using GCC C compiler.
First, create a project directory (I am going to call it hello) with the following command:
Now navigate to the newly created directory with the following command:
Now create a new C source file (I am going to call it main.c) here with the following command:
Now open the file with any text editor (such as vim, nano, gedit, kate etc) of your choice.
To open the file with nano, run the following command:
To open the file with vim, run the following command:
To open the file with Gedit, run the following command:
To open the file with Kate, run the following command:
I am going to use Gedit text editor in this article.
Now type in the following lines and save the file.
Here, line 1 includes the stdio.h header file. It has function definition for the printf() function I used on line 4.
Every C program must have a main() function. It is the function that will get called when you run a C program. If you don’t write a main() function, you can’t run the C program. So I wrote a main() function in line 3 – line 7.
Inside the main() function, I called printf() library function in line 4 to print some text to the screen.
Finally, in line 6, I returned 0 from the program. On Linux world, when a program returns 0, it means the program ran successfully. You can return any integer you like but there are some Linux specific rules on what return value means what.
In the next section, I will show you how to compile the C program with GCC and run it.
Compiling and Running C Programs with GCC:
The command to compile a C source file with GCC is:
NOTE: Here, SOURCE_FILES is a whitespace separated list of C source files. The compiled executable file will be saved as OUTPUT_BINARY in your current working directory.
In our case, the main.c source file doesn’t depend on other C source file, so we can compile it with the following command:
The source file main.c should be compiled and hello executable file should be created as you can see in the screenshot below.
Now, you can run the hello executable binary file as follows:
As you can see, the correct output is printed on the screen.
So that’s basically how you use GCC to compile C programs on Linux. Thanks for reading this article.
Источник