How to compile a C file using GCC in Linux?

The method for compiling C files in Linux using gcc is as follows:

  1. Open the terminal and navigate to the directory where the C file is located.
  2. Compile the C file using the following command:
  3. Compile the input_file.c and generate an executable output_file.
  4. 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.
  5. If the compilation is successful, no error messages will be displayed in the terminal. To run the compiled executable file, use the following command:
  6. 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!”.

bannerAds