Compiling a C Program
Let’s explore creating and compiling a C program. Before you begin, open Visual Studio Code either on the CS Desktop or natively on your computer.
NOTE: Be sure to set up Visual Studio Code before you continue.
Create a file named hello.c
by navigating to File -> New File
and type the following code into it:
#include <stdio.h>
int main()
{
printf("Hello, World!\n");
return 0;
}
You will need access to a Terminal in order to compile and run your code. To open one in Visual Studio Code, click Terminal -> New Terminal
. You should be presented with a shell that allows you to type in textual commands.
$
Try typing gcc --version
to verify that the gcc
compiler is available. You should see something like the following:
$ gcc --version
gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
Then you can try to compile your hello.c
file by typing:
$ gcc hello.c
This command executes the gcc
compiler on the hello.c
file which ought to produce an executable file named a.out
(a.exe
if you are on Windows). To execute your program, type:
$ ./a.out
Hello, world!
If this worked, you’re all set! You should be able to write C programs by creating files with a .c
extension, and then compiling them using gcc
like we did above.