- 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?
- С compilation command in linux
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.
Источник
С compilation command in linux
GENERATE LINUX KERNEL COMPILATION DATABASE
A modern Linux host
Though Ubuntu 16.04 used here, any modern Linux Distributions should work. Tested on Arch Linux.
python2 or python3 compiledb command
- decompress the source tar ball
Notice: the path of the ncurses library on your host system may be not at the position as old linux expected.
To fix it, install ncurses lib via your package manager and then modify scripts/lxdialog/Makefile:29 as follows:
Let gcc find libncurses automatically. Then rerun make menuconfig.
This does not compile the kernel actually, just dryrun.
Add more general CFLAGS, some index backend engines might need them.
- decompress the source tar ball
Notice: the path of the ncurses library on your host system may be not at the position as old linux expected.
To fix it, install ncurses lib via your system package manager and then modify scripts/lxdialog/Makefile:29 as follows:
Let gcc find libncurses automatically. Fix a bug in scripts/lxdialog/lxdialog.c:60 before going on.
Then rerun make menuconfig.
This does not compile the kernel actually, just dryrun.
Add more general CFLAGS, some index backend engines might need them.
- decompress the source tar ball
Notice: the path of the ncurses library on your host system may be not at the position as old linux expected.
To fix it, install ncurses lib via your system package manager and then modify scripts/lxdialog/Makefile:28 as follows:
Let gcc find libncurses automatically. Then rerun make ARCH=i386 menuconfig.
This does not compile the kernel actually, just dryrun.
Add more general CFLAGS, some index backend engines might need them.
- decompress the source tar ball
This does not compile the kernel actually, just dryrun.
Some index backend engines may not work well using this compile_commands.json, since some CFLAGS needed by modern x86_64 compilers are missing in old kernel config. Add -m32 to the compile_commands.json:
- decompress the source tar ball
This does not compile the kernel actually, just dryrun.
Some index backend engines may not work well using this compile_commands.json, since some CFLAGS needed by modern x86_64 compilers are missing in old kernel config. Add -m32 to the compile_commands.json:
- decompress the source tar ball
This does not compile the kernel actually, just dryrun. The fail of the final linkage of vmlinux does not matter, since the total compilation has finished.
- decompress the source tar ball
choose ARCH, i386 or x86_64
or just use a common default config, and skip step 3.
Note: The Makefile in src root dir has syntax error using modern make, fix that first.
This does not compile the kernel actually, just dryrun. The fail of the final linkage of vmlinux does not matter, since the total compilation has finished.
- decompress the source tar ball
choose ARCH, i386 or x86_64
This config will base on your host’s /boot/config of the host kernel.
or just use a common default config
You may need to make menuconfig again after make defconfig to disable the “Device Drivers -> Graphics support -> Bootup logo”, which causes the dryrun fail prematurely. If you want a real compilation of the kernel source, just skip this step after make defconfig.
[OPTIONAL] prepare a real compilation of the kernel if you want
a. install gcc-4.x multilib to support the compiling, here I use 4.6, 4.9 should be ok, not tested
b. modify a Makefile to support gcc 4.x to compile
c. perl scritps may need to be modified to support more recent perl interpreter, e.g.
note: [a] and [b] are exclusive, use one of them according to real compile or dryrun.
[a]. do a real compilation of the kernel and get the build log, this requires step[4]
ARCH x86_64 should be the same as i386, the gcc-4.x multilib version should be used if both i386 and x86_64 need to be supported.
[b]. get the build log using make dryrun, if not real compilation
Before we can dryrun, “Device Drivers -> Graphics support -> Bootup logo” should be disabled.
Linux 3.x — latest
- The 3.x and 4.x versions should be the same as 2.6.34. If dryrun fails, fix the problems or JUST DO A REAL [CROSS] COMPILATION on your host. The difference may be that the gcc version used is varied.
- Since kernel v5, scripts/gen_compile_commands.py can be used to generate the compile_commands.json natively. Just compile the kernel, and run the script. e.g.
Bonus: Linux 0.12
- decompress the source tar ball
note: [a] and [b] are exclusive, use one of them.
[a]. use linux-0.12-gen_build_log.sh to generate the build log
[b]. or use linux-0.12-gen_build_log.mk to generate the build log
Dry-Run vs Real Compilation
The compile database of a real compilation get all the files involved in the compilation. The compile database of dry-run might miss some seperate targets despite all the kernel vmlinux compilation commands that successfully generated. The missing targets are mostly in arch/$ARCH/boot/, and some helping tools and scripts. Files in arch/$ARCH/boot of ancient kernel source are mostly ASM files, which are not able to be indexed by clang based C/C++ indexers. Routines or symbols in the .S asm files can be easily found via grep tools like ripgrep . The arch/$ARCH/boot of relatively new kernels can be indexed via a real compilation.
Источник