For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
C is one of the most widely used programming languages, and Linux provides a powerful environment for compiling and running C programs. The GNU Compiler Collection (GCC) is the standard compiler used for this purpose.
Understanding how to compile and execute a C program in Linux is essential for students learning programming or working on projects. This guide explains every step, from writing a simple program to debugging errors, ensuring you can confidently compile and run C programs on Linux.
Before compiling and running a C program in Linux, you need a few essential tools and a proper setup. Having the right environment ensures a smooth compilation process without unexpected errors. Below are the basic requirements you must check before proceeding.
If it displays a version number, GCC is installed. If not, you need to install it, which is covered in the next section.
GCC (GNU Compiler Collection) is the most commonly used C compiler in Linux. Without it, you cannot compile C programs. Some Linux distributions come with GCC pre-installed, but you must verify it before proceeding. If it is not installed, you will need to install it manually using the package manager for your Linux distribution.
Before installing GCC, check if it is already available on your system. Open the terminal and run the following command:
gcc --version
If GCC is installed, you will see output like this:
gcc (Ubuntu 11.3.0-1ubuntu1) 11.3.0
Copyright (C) 2022 Free Software Foundation, Inc.
This means your system already has GCC installed, and you can move to the next section. If you see an error or a message like command not found, you need to install GCC.
Different Linux distributions use different package managers. Below are the installation commands for major distributions. Use the command that matches your system.
Ubuntu/Debian – These distributions use the apt package manager. Install GCC by running:
sudo apt update
sudo apt install build-essential
The build-essential package includes GCC, g++, and other necessary tools.
Fedora – Fedora uses the dnf package manager. To install GCC, run:
sudo dnf groupinstall "Development Tools"
This installs GCC along with other essential development packages.
Arch Linux – Arch Linux users can install GCC using pacman:
sudo pacman -S base-devel
The base-devel package includes GCC and additional development tools.
After installing GCC, confirm that it works correctly by running:
gcc --version
Also Read: Linux Tutorial for Beginners – Step by Step Linus Guide
If the installation was successful, you will see the version details, indicating that GCC is ready to use. You can now proceed to writing and compiling your first C program.
Before compiling and running a C program, you need to write the source code in a .c file. Linux does not come with a built-in code editor, but you can use any text editor like Nano, Vim, or VS Code. This section guides you through creating a simple C program and understanding its basic structure.
To start, open the terminal and navigate to the directory where you want to save your C program. Then, use the nano editor to create a new file:
nano hello.c
This command opens a blank file named hello.c in the Nano text editor. If you prefer Vim, use:
vim hello.c
Or for VS Code:
code hello.c
Once the editor opens, you can begin writing your program.
A simple C program consists of a few essential components: header files, a main() function, and output statements. Below is a basic C program that prints a message:
#include <stdio.h> // Standard Input-Output library
int main() {
printf("Hello, Linux!\n"); // Print output to the screen
return 0; // Return 0 to indicate successful execution
}
This program includes:
Once you have written the code, save and close the file:
Your C program is now ready for compilation. In the next section, you will learn how to compile it using GCC.
Once you have written your C program, the next step is to compile it. Computers do not understand C directly. You must convert the human-readable source code into machine code that the system can execute. This process is called compilation, and it is done using the GCC compiler.
When you run a C program, the GCC compiler takes your .c file and performs the following steps:
These steps happen in the background when you use GCC, but knowing them helps in debugging errors later.
To compile your C program, open the terminal and run:
gcc hello.c -o hello
This command tells GCC to:
If there are no errors, GCC will complete the compilation silently. This means no message is displayed unless an error occurs.
If there are mistakes in your code, GCC will show error messages. For example:
hello.c: In function 'main':
hello.c:3:5: error: expected ';' before 'return'
return 0;
^
This error means a semicolon is missing before return 0;. Always read the error messages carefully, as they tell you the line number and nature of the mistake.
Even if your program compiles, it might still have issues. To enable warnings, use:
gcc -Wall hello.c -o hello
Using warnings helps you write better and more reliable code. Now that the program is compiled, the next step is to run it.
Once you have successfully compiled your C program, the next step is to run it. The compilation process generates an executable file that contains machine code, which the system can execute directly. On Linux, you need to use the terminal to run the program.
By default, if you compile a program without specifying an output filename, GCC creates an executable named a.out. However, if you used the -o flag during compilation, your output file will have the specified name. In the previous section, you compiled your program using:
gcc hello.c -o hello
This command creates an executable file named hello. You can check if the file was created by listing the files in the directory:
ls
If the compilation was successful, you should see hello in the list of files.
Unlike Windows, where you can simply double-click an executable file, Linux requires you to explicitly tell the system to execute a program in the current directory. To run your compiled program, use:
./hello
If everything is correct, the program will output:
Hello, Linux!
Sometimes, running the program may result in an error. Common issues include:
Permission Denied:
bash: ./hello: Permission denied
This means the file does not have execute permissions. Fix this by running:
chmod +x hello
Command Not Found:
bash: hello: command not found
If you want to run your program by simply typing hello instead of ./hello, move the executable to a directory listed in your system’s PATH variable:
mv hello /usr/local/bin/
After this, you can run the program from any location by just typing:
hello
This is useful for frequently used programs or scripts.
Now that you know how to run a compiled program, you can test it with different inputs and outputs, which will be covered in the next section.
Errors are a common part of programming, especially for beginners. When compiling a C program in Linux, the GCC compiler helps by displaying error messages that indicate what went wrong. Understanding these errors will save time and help you write correct code.
There are different types of errors you may encounter while compiling a C program. Below are the most common ones and how to fix them.
Syntax errors occur when you write incorrect C code that does not follow language rules. For example, missing semicolons or using incorrect keywords.
Example:
#include <stdio.h>
int main() {
printf("Hello, Linux!") // Missing semicolon
return 0;
}
Compilation Command:
gcc hello.c -o hello
Error Output:
hello.c: In function 'main':
hello.c:3:5: warning: implicit declaration of function 'print' [-Wimplicit-function-declaration]
print("Hello, Linux!");
^~~~~
Solution: Add a semicolon at the end of the printf statement.
If your program calls a function that has not been defined or included, the compiler will show an error.
Example:
int main() {
printf("%d", num); // Variable 'num' is not declared
return 0;
}
Compilation Command:
gcc hello.c -o hello
Error Output:
hello.c: In function 'main':
hello.c:3:5: warning: implicit declaration of function 'print' [-Wimplicit-function-declaration]
print("Hello, Linux!");
^~~~~
Solution: Use printf() instead of print(), and include <stdio.h> if missing.
Braces {} and parentheses () must be used correctly.
Example:
int main( {
printf("Hello, Linux!\n");
return 0;
}
Compilation Command:
gcc hello.c -o hello
Error Output:
hello.c: In function 'main':
hello.c:1:9: error: expected ')' before '{'
int main( {
^
Solution: Change int main( { to int main() {.
Using a variable that has not been declared results in an error.
Example:
int main() {
printf("%d", num); // Variable 'num' is not declared
return 0;
}
Compilation Command:
gcc hello.c -o hello
Error Output:
hello.c: In function 'main':
hello.c:3:17: error: 'num' undeclared (first use in this function)
printf("%d", num);
^
Solution: Declare the variable before using it:
int num = 10;
printf("%d", num);
Even if your program compiles successfully, it may contain warnings that indicate potential issues. You can enable warnings with:
gcc -Wall hello.c -o hello
Example Warning Output:
hello.c: In function 'main':
hello.c:3:5: warning: unused variable 'x' [-Wunused-variable]
int x = 5;
^
This warns that the variable x is declared but never used. Fixing such warnings improves code quality.
To debug errors quickly:
By understanding and fixing these errors, you will improve your coding skills and write more reliable programs. In the next section, you will learn how to enable debugging and use tools like gdb to troubleshoot runtime issues.
Even if your C program compiles successfully, it might still contain potential issues. These could be unused variables, missing return statements, or incorrect data types. Ignoring these warnings can lead to unexpected behavior when the program runs. Enabling compiler warnings and using debugging tools help identify and fix these issues early.
By default, the GCC compiler does not show warnings unless they cause a compilation error. However, you can enable them using the -Wall flag:
gcc -Wall hello.c -o hello
This command tells GCC to display common warnings that might indicate problems in the code.
Code with Warning:
#include <stdio.h>
int main() {
int x = 10; // Variable 'x' is declared but not used
printf("Hello, Linux!\n");
return 0;
}
Compilation Command:
gcc -Wall hello.c -o hello
Warning Output:
hello.c: In function 'main':
hello.c:4:9: warning: unused variable 'x' [-Wunused-variable]
int x = 10;
^
Solution: If you do not need the variable, remove it. Otherwise, ensure it is used in the program.
Apart from -Wall, you can use other flags for stricter checks:
Example of enabling all these warnings:
gcc -Wall -Wextra -Werror hello.c -o hello
Some issues do not appear during compilation but cause problems when the program runs. These are called runtime errors and can be difficult to locate. The GNU Debugger (gdb) helps you track these errors by allowing you to inspect how your program executes.
To use gdb, you must compile your program with the -g flag:
gcc -g hello.c -o hello
This includes debugging information in the executable without affecting normal execution.
Run gdb with the compiled program:
gdb hello
You will see an output similar to:
GNU gdb (GDB) 12.1
Reading symbols from hello...
(gdb)
This means the debugger is now ready to analyze your program.
Breakpoints allow you to pause the program at a specific line and examine variables. To set a breakpoint at line 5, use:
break 5
Then, start execution with:
run
If the program reaches line 5, it will pause, allowing you to inspect variables before continuing.
Use the print command to check variable values:
print x
This helps find unexpected values or incorrect calculations.
Once you examine the paused state, you can:
continue
next
When finished, exit gdb by typing:
quit
Common Runtime Errors and How to Debug Them
Even if your program compiles without errors, it might still crash or behave unexpectedly while running. These are called runtime errors, and they occur due to issues like invalid memory access, infinite loops, or incorrect logic.
Debugging such errors requires understanding what causes them and how to fix them using tools like gdb. Below are some of the most common runtime errors and how you can debug them effectively.
A segmentation fault occurs when a program tries to access an invalid memory location.
Example Code:
int main() {
int *ptr = NULL; // Pointer is set to NULL
*ptr = 10; // Attempting to write to NULL (Invalid memory access)
return 0;
}
Error Output (when run):
Segmentation fault (core dumped)
Solution: Check if a pointer is NULL before accessing it.
A loop that never ends can freeze a program.
Example Code:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) { // 'i' is never updated
printf("Looping...\n");
}
return 0;
}
Issue: The value of i never changes, so the loop runs forever.
Solution: Ensure loop conditions are correctly updated:
while (i < 5) {
printf("Looping...\n");
i++; // Increment i to avoid infinite looping
}
Understanding warnings and debugging tools helps you write better, error-free programs. In the next section, you will learn how to handle input and output efficiently using redirection in Linux.
In Linux, you can run a compiled C program normally by executing its output file. However, sometimes you may need to provide input to your program or save its output for later use.
Instead of manually typing input or copying output, Linux allows input and output redirection, which makes working with programs more efficient. This is particularly useful when handling large amounts of data or automating tasks.
Input redirection (<) allows a program to read data from a file instead of requiring manual input from the keyboard. This is useful for programs that process large datasets or require repeated testing.
Output redirection (>) saves the output of a program into a file instead of displaying it on the terminal. This helps when you want to store results for further analysis or debugging.
If your program requires user input, instead of entering it manually each time, you can provide input from a file. First, create an input file using a text editor like Nano:
nano input.txt
Enter some sample data in the file and save it. Now, modify your C program to take input from the user:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
Compile the program using:
gcc input_example.c -o input_example
Instead of typing a number manually, you can redirect input from input.txt by running:
./input_example < input.txt
If input.txt contains the number 42, the output will be:
Enter a number: You entered: 42
This is useful when testing programs that require user input multiple times.
To save the output of a program to a file instead of displaying it on the terminal, use >. Modify the previous program slightly so that it prints a series of numbers:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Number: %d\n", i);
}
return 0;
}
Compile and run the program:
gcc output_example.c -o output_example
./output_example > output.txt
Now, instead of printing on the screen, the output is stored in output.txt. You can view the file’s contents using:
cat output.txt
The file will contain:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
This is useful when working with large outputs that need to be reviewed or processed later.
You can combine both input and output redirection in a single command. Suppose your program takes input from a file and prints a result. You can redirect both input and output as follows:
./program < input.txt > output.txt
This command reads input from input.txt and saves the output in output.txt without displaying anything on the terminal.
If you use >, it will overwrite the existing content of a file. To append output to an existing file instead of replacing it, use >>.
./output_example >> output.txt
This adds new output at the end of output.txt instead of deleting previous content.
Summary of Input and Output Redirection
Input and output redirection are powerful features that help automate testing, store program results, and process large amounts of data efficiently. In the next section, you will learn how to compile and run programs that use multiple C files.
As your C programs become more complex, writing everything in a single file becomes difficult to manage. To improve organization and reusability, large programs are often split into multiple files. This method allows you to separate logic into different components, making debugging and maintenance easier.
When you break a program into multiple files, you can:
To demonstrate how multiple files work, you will create a main file and a separate function file that contains a helper function.
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
#ifndef MATH_FUNCTIONS_H
#define MATH_FUNCTIONS_H
// Function prototype
int add(int a, int b);
#endif
#include <stdio.h>
#include "math_functions.h" // Include the function header file
int main() {
int num1 = 5, num2 = 10;
int sum = add(num1, num2); // Call function from another file
printf("Sum: %d\n", sum);
return 0;
}
In this structure:
Also Read: 25 Most Common C Interview Questions & Answers [For Freshers]
You cannot compile main.c alone because it depends on math_functions.c. Instead, compile both files together:
gcc main.c math_functions.c -o program
This tells GCC to:
Run the program:
./program
Expected Output:
Sum:
15
Instead of compiling all files at once, you can compile them separately and then link them together:
gcc -c math_functions.c -o math_functions.o
gcc -c main.c -o main.o
gcc main.o math_functions.o -o program
This method:
Running ./program will produce the same output:
Sum: 15
If your program has many functions, separate compilation speeds up development since you do not need to recompile everything after every change.
When you are working with libraries, compiling separately allows for better code organization and reuse.
Also Read: Top 9 Popular String Functions in C with Examples Every Programmer Should Know in 2025
Using multiple files makes C programs scalable and easier to manage. In the next section, you will learn how to automate compilation using a Makefile instead of manually running multiple commands.
Manually compiling and running C programs in the terminal is a great way to understand how compilation works. However, for larger projects, using an Integrated Development Environment (IDE) can make coding easier and more efficient.
An IDE provides features like syntax highlighting, debugging tools, and built-in compilation, allowing you to focus on writing code rather than managing compilation commands. This section covers some lightweight yet powerful IDEs available for Linux.
While you can use simple text editors like Nano or Vim, IDEs offer several advantages that improve productivity.
Using an IDE can significantly improve your programming experience, especially if you are a beginner learning C. Below are some of the best IDEs for Linux that support C programming.
There are several IDEs available for Linux, but not all of them are optimized for C programming. The table below compares some popular choices.
IDE Name | Installation Command | Key Features |
VS Code | sudo snap install --classic code | Lightweight, extensions for debugging and C programming support |
Code::Blocks | sudo apt install codeblocks | Simple UI, built-in compiler, and debugger |
Geany | sudo apt install geany | Fast, supports multiple languages, low resource usage |
Eclipse CDT | Install via Eclipse Marketplace | Best for large C/C++ projects, powerful debugging tools |
Also Read: Top 25+ C Programming Projects for Beginners and Professionals
Each IDE has different features, but the basic setup process remains the same. Below is a general guide to setting up an IDE for C programming.
Choose an IDE and install it using your Linux package manager. For example, to install VS Code, run:
sudo snap install --classic code
To install Geany:
sudo apt install geany
Open the IDE and create a new file named hello.c. Write a simple C program:
#include <stdio.h>
int main() {
printf("Hello from an IDE!\n");
return 0;
}
Most IDEs have a Run or Build button that automatically compiles and executes the program. If using VS Code, install the C/C++ Extension Pack and run:
gcc hello.c -o hello && ./hello
Expected output:
Hello from an IDE!
Not all IDEs are suitable for every project. Here’s how to choose the right one:
Also Read: Difference Between C and Java: Which One Should You Learn?
Using an IDE can make programming in C much easier by simplifying compilation, debugging, and project management.
Now that you have learned how to compile and run C program in Linux, it's time to test your understanding. Below are 10 multiple-choice questions (MCQs) covering key concepts, common errors, debugging techniques, and best practices. Choose the correct answer for each question.
1. Which command is used to check if GCC is installed on your Linux system?
A) gcc --help
B) gcc --version
C) gcc --install
D) gcc -compile
✅ Correct Answer: B) gcc --version
2. What does the following command do?
gcc program.c -o output
A) Runs the C program
B) Compiles program.c and creates an executable named output
C) Opens program.c in a text editor
D) Compiles and runs the program in one step
✅ Correct Answer: B) Compiles program.c and creates an executable named output
3. What will happen if you try to run a compiled C program using only the filename, like this?
output
A) The program will execute normally
B) The terminal will show "Command not found"
C) The program will delete itself
D) It will open in a text editor
✅ Correct Answer: B) The terminal will show "Command not found"
4. Which flag enables warnings during compilation?
A) -debug
B) -error
C) -Wall
D) -warn
✅ Correct Answer: C) -Wall
5. If a program needs user input, which redirection symbol allows input from a file instead of the keyboard?
A) >
B) >>
C) <
D) |
✅ Correct Answer: C) <
6. What is the purpose of the following command?
chmod +x output
A) Compiles the C program
B) Grants execute permission to the output file
C) Deletes the output file
D) Runs the program in debug mode
✅ Correct Answer: B) Grants execute permission to the output file
7. Which debugging tool is commonly used in Linux to analyze runtime errors in C programs?
A) gcc
B) nano
C) gdb
D) vim
✅ Correct Answer: C) gdb
8. What happens when you use >> instead of > for output redirection?
A) The output is erased before new content is written
B) The output is added at the end of the existing file content
C) The program runs in the background
D) The output is displayed on the screen instead of being saved
✅ Correct Answer: B) The output is added at the end of the existing file content
9. How do you compile multiple C files (main.c and math.c) together using GCC?
A) gcc main.c -o math.c program
B) gcc main.c math.c -o program
C) gcc -c main.c math.c -o program
D) gcc -m main.c math.c program
✅ Correct Answer: B) gcc main.c math.c -o program
10. What is the main purpose of a Makefile in C programming?
A) It runs the program automatically
B) It speeds up compilation by managing dependencies
C) It removes all compiled files
D) It replaces the need for gcc
✅ Correct Answer: B) It speeds up compilation by managing dependencies
The more you practice, the better you get at programming. Keep testing your knowledge and improving your skills!
Learning C programming is a valuable skill that opens the door to software development, system programming, and embedded systems. If you want to strengthen your programming skills, gain hands-on experience, and build a strong career, upGrad can support your journey.
upGrad is a leading online learning platform with over 10 million learners, offering 200+ expert-led courses and partnerships with 1400+ hiring companies. Whether you are just starting with C or want to expand into software development, data science, or cloud computing, you will find industry-relevant programs tailored to your goals.
If you want to develop strong coding skills, work on real-world projects, and earn certifications, the following upGrad courses will be a great fit:
If you are unsure which course aligns with your career goals, upGrad’s career counseling team is here to guide you. Get a free one-on-one session with an expert who will help you understand your options, suggest the right learning path, and provide career guidance tailored to your skills.
Similar Reads:
A Complete Guide to Master Linux Commands for DevOps in 2025
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Discovering C Operators: An Overview with Types and Examples!
Fibonacci Series Program in C Using Recursion
Format Specifiers in C Programming
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Addition of Two Numbers in C: A Comprehensive Guide to C Programming
C Program to check Armstrong Number
C Enum Type: Definition and Practical Implementation
Factorial Program of a Number in C
15 Most Important Features of C Language
Q: How Do You Cross-Compile a C Program for a Different Architecture?
A: Use a cross-compiler like GCC configured for the target architecture to compile your C program accordingly.
Q: What Is the Purpose of the -pthread Flag in GCC?
A: The -pthread flag enables multithreading with the POSIX threads library, linking and compiling thread-related functions.
Q: How Can You Optimize a C Program During Compilation?
A: Use GCC optimization flags like -O2 or -O3 to enhance performance by enabling various optimization techniques.
Q: What Does the -static Flag Do When Compiling a C Program?
A: The -static flag compiles the program with static linking, including all library dependencies within the executable.
Q: How Do You Generate Assembly Code from a C Source File?
A: Use the -S flag with GCC to compile the C source file into an assembly language file for examination.
Q: What Is the Role of the -D Option in GCC Compilation?
A: The -D option defines macros during compilation, allowing conditional code inclusion or configuration settings.
Q: How Can You Include Debugging Symbols in a Compiled C Program?
A: Compile the program with the -g flag to include debugging information, facilitating source-level debugging.
Q: What Is Position-Independent Code (PIC), and When Is It Used?
A: PIC allows code to execute correctly regardless of its memory address, commonly used in shared libraries.
Q: How Do You Specify a Custom Library Path During Compilation?
A: Use the -L flag to specify directories for the linker to search for libraries during the compilation process.
Q: What Is the Effect of the -fPIC Flag in GCC?
A: The -fPIC flag generates position-independent code, essential for creating shared libraries in C programs.
Q: How Can You Suppress Specific Compiler Warnings in GCC?
A: Use the -Wno-<warning> flag to disable specific warnings, customizing the compiler's feedback during compilation.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.