Compiling C programs in Linux is commonly done using the GCC (GNU Compiler Collection). It translates your .c source files into executable programs.
Setting Up Your Environment
1. Install GCC Compiler
GCC (GNU Compiler Collection) is the standard compiler for C in Linux. To install it, open your terminal and run:
sudo apt update
sudo apt install build-essential
This command installs GCC along with other essential tools like make and libraries required for compiling C programs.
2. Verify GCC Installation
After installation, confirm that GCC is installed correctly:
gcc --version
You should see the GCC version information displayed.
Writing Your First C Program
Use any text editor like nano, vim, or gedit to write your code.
nano quiz.c
Example: quiz.c
#include <stdio.h> int main() { printf("Welcome to Sanfoundry Quiz!\n"); return 0; }
Compiling the C Program
1. Basic Compilation
To compile your C program, use the gcc command:
gcc quiz.c -o quiz
This command tells GCC to compile quiz.c and output an executable named quiz.
2. Run the Executable
After compiling, run the program:
./quiz
Output:
Welcome to Sanfoundry Quiz!
GCC Compilation Stages
GCC compiles C programs through several stages:
- Preprocessing: Handles directives like #include and #define.
- Compilation: Translates preprocessed code into assembly language.
- Assembly: Converts assembly code into machine code, producing object files.
- Linking: Combines object files and libraries into an executable.
You can observe these stages using GCC flags:
- Preprocessing Only:
- Compile to Assembly:
- Compile to Object File:
- Link Object File to Create Executable:
gcc -E quiz.c -o quiz.i
gcc -S quiz.c -o quiz.s
gcc -c quiz.c -o quiz.o
gcc quiz.o -o quiz
Optional GCC Flags:
Flag | Purpose |
---|---|
-Wall | Enables all warnings |
-Werror | Treats warnings as errors |
-g | Includes debugging information |
-O2 | Optimization level |
-std=c99 | Use C99 standard |
Mini Compilation Example
#include <stdio.h> #define test 100 int main() { printf("Sanfoundry test score = %d\n", test); return 0; }
To compile:
gcc test.c -o test
To run:
./test
Output:
Sanfoundry test score = 100
Troubleshooting Common Issues
- Command Not Found: If you receive a “command not found” error for gcc, ensure that GCC is installed and added to your system’s PATH.
- Permission Denied: If you encounter a “permission denied” error when running your executable, ensure it has execute permissions:
- Segmentation Fault: This indicates an error in your code, such as accessing invalid memory. Review your code for mistakes.
chmod +x test
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice BCA MCQs
- Apply for C Internship
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Check C Books