Getting started with C programming - Setup (Linux) -
There's 3 things you need to do: install a compiler → write some code → give the code to the compiler.
This page is for Linux. You can also check the Windows version.
Setup tools
Open command line (Terminal)
You don't need to start using it, but the compiler must be started with a command line command so it's good to know the idea behind it.
To open it, press Ctrl+Alt+T.
Quick terminal guide:
- To find out what's in the current folder, type
ls
. - Type
cd foldername
to enter a folder,cd ..
to exit folder. Press Tab to auto-complete folder/file names. - Press Up and Down arrow keys to browse previously entered commands.
- Type the name of a program to run that program. Anything you type after the program name will be given to that program, for example
compilername mycode.c
. - Press Ctrl+C to exit whatever program is running, it will be important when you run your own program.
Install the compiler
You need a compiler to turn your code into a program. We'll use GCC.
It may already be installed on your Linux distribution. On the terminal, type gcc --version
, you should get information about the GCC version.
If you get an error like "Command not found", then GCC hasn't been installed. You can install GCC on some Linux distributions by typing sudo apt install gcc
into the terminal.
Make a test program
Save the code below as "main.c":
#include <stdio.h> int main () { printf("Bag of biscuits\n"); return 0; }
Now you just need to give the code to GCC. You can do it with a terminal command like gcc main.c -o testprogram
, but a better way is to create a build file that will do all the commands that you want.
Save the below as "build.sh" into the same folder:
#!/bin/sh # Compile the code. if gcc main.c -o testprogram ; then # If successfully compiled without errors, run the program. ./testprogram fi
On the terminal, navigate to the folder and type chmod u+x build.sh
to make the build script executable (you only need to do this once). Then type ./build.sh
to run it, it will create your program and immediately runs it. Your program should print "Bag of biscuits" onto the terminal. If there's errors in your code file, GCC will print a bunch of error messages.
Note: You must add ./
in the beginning to run a program from the current folder. When you install a program like gcc, it's location is added into your PATH variable, which is why you can run it simply by typing gcc
.
Search "linux PATH variable" from a search engine if you want to learn more.