How to compile a C file using GCC in Linux?
The method for compiling C files in Linux using gcc is as follows:
- Open the terminal and navigate to the directory where the C file is located.
- Compile the C file using the following command:
- Compile the input_file.c and generate an executable output_file.
- output_file is the name of the executable file generated after compilation, and input_file.c is the name of the C source code file to be compiled.
- If the compilation is successful, no error messages will be displayed in the terminal. To run the compiled executable file, use the following command:
- Save the output to a file named “output_file”.
Here is a complete example:
Suppose there is a C file named hello.c containing the following code:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Navigate to the directory where the file is located in the terminal, and compile using the following command:
gcc -o hello hello.c
If the compilation is successful, no error messages will be displayed in the terminal. Then, use the following command to run the generated executable file:
./hello
The terminal will display “Hello, World!”.