Getting started with C programming - Setup -
There's 3 things you need to do: install a compiler → write some code → give the code to the compiler.
Setup tools
Open command line
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.
(CMD): press Win+R, then type cmd into the box.
(Terminal): press Ctrl+Alt+T.
Quick command line guide:
- To find out what's in the current folder, type
dir
on Windows orls
on Linux. - 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.
You'll need to install MingW (which includes GCC):
https://sourceforge.net/projects/mingw/
Alternately, you can get an unofficial version from here without having to enable javascript:
https://nuwen.net/mingw.html (mingw-XXX-without-git.exe)
You might already have GCC. If not you can install it on some Linux distributions by typing
sudo apt install gcc
into the command line.
On the command line, type gcc --version
to test if it works, you should get some information about the GCC version. You can also just type the full path to the compiler executable, for example: "C:/Users/Sun/MinGW/bin/gcc.exe" --version
.
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 command line command like gcc main.c -o testprogram
, but a better way is to create a build file that will do the commands for you, so you only need to type build
.
Save the below as "build.bat" into the same folder:
@ECHO OFF rem Compile the code. gcc main.c -o testprogram && ( rem If successfully compiled without errors, run the program. testprogram ) pause
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 command line, navigate to the folder and type chmod u+x build.sh
to make the build script executable.
On command line, navigate to the folder that has your build script and main.c code file. Type build
on Windows, or ./build.sh
on Linux, the build script will create your program and immediately runs it. Your program should print "Bag of biscuits" onto the command line. If there's errors in your code file, GCC will print a bunch of error messages.