
{{ $('Map tags to IDs').item.json.title }}
How to Compile C Programs on Linux Using GCC
The GNU Compiler Collection (GCC) is a widely used compiler for C and other programming languages on Linux systems. This tutorial will guide you through the process of compiling C programs with GCC.
Prerequisites
- A Linux system with terminal access.
- GCC installed on your system.
- Basic knowledge of C programming.
1. Installing GCC
Most Linux distributions come with GCC pre-installed. To check if GCC is installed, run:
gcc --version
If GCC is not installed, you can install it using the package manager:
- For Ubuntu/Debian:
sudo apt update sudo apt install build-essential -y
- For CentOS/RHEL:
sudo yum groupinstall 'Development Tools' -y
- For Fedora:
sudo dnf groupinstall 'Development Tools' -y
2. Writing a Simple C Program
Now that you have GCC installed, you can write a simple C program. Open your text editor and create a file named hello.c
:
nano hello.c
Add the following code to the file:
#include
int main() {
printf("Hello, World!\n");
return 0;
}
Save and exit the editor.
3. Compiling the C Program
To compile your C program using GCC, run the following command:
gcc hello.c -o hello
In this command:
- hello.c: The source file you want to compile.
- -o hello: This option specifies the name of the output executable file. If you omit this option, the default name will be
a.out
.
4. Running the Compiled Program
To run your compiled program, execute:
./hello
You should see the following output:
Hello, World!
5. Handling Compilation Errors
If there are any syntax errors in your code, GCC will print error messages to the terminal. Review the messages to identify and correct the errors in your code.
6. Compiling Multiple Source Files
If your program has multiple source files, compile them together like this:
gcc file1.c file2.c -o my_program
7. Using Compiler Flags
GCC provides various flags to optimize the compilation process:
- -Wall: Enables all the basic warning messages.
- -O2: Enables a set of optimization flags for better performance.
Example command with flags:
gcc -Wall -O2 hello.c -o hello
8. Conclusion
By following this tutorial, you have learned how to set up GCC, write a simple C program, and compile it on Linux. Utilize these skills to expand your knowledge in C programming and efficiently build your applications.