Crash Course in C

Author: Beau Christ

NOTE: THIS TUTORIAL IS UNDER DEVELOPMENT, AND WILL BE PERIODICALLY UPDATED.

How To Compile and Run Your C Programs

We will use the gcc compiler. To compile a C source code file, navigate to the directory where your source code file is located, then type gcc -o nameOfProgram fileToCompile.c. The -o flag is optional to give your executable program a better name than a.out. To run your program, simply type ./nameOfProgram, as long as you are in the same directory as your program.

So, if you created a program called hello.c, compile it with:

gcc -o hello hello.c

and run it with:

./hello

Useful gcc Flags

To check for compliance to a specific version of C, such as C11:

gcc -std=c11 -o hello hello.c

To display all warning messages:

gcc -Wall -o hello hello.c

If you would like to see the assembly code that gets generated:

gcc -S hello.c

To see each step of the compilation:

gcc -v hello.c

If you need to utilize an external library (such as /usr/lib/):

gcc -L/usr/lib hello.c

And of course, you can combine multiple flags together:

gcc -std=c11 -Wall -o hello -v -L/usr/lib hello.c

For more help with gcc:

gcc -help

A First Program

A good first practice program is a typical “Hello, world!” program. Create a new file (if you are at the Linux command line, you can do this with nano hello.c). In the new file, type out the following program:

#import "stdio.h"

int main() {
  printf("Hello, COSC 365!\n");
  
  return 0;
}

Now save it, and try to compile it with gcc -o hello hello.c, then run it with ./hello. If you get errors after compiling, you will need to reopen your C program using nano hello.c, fix the issue, save, then recompile.

Data Types

The most common data types in C are:

int     // integer
float   // floating point
char    // single character, such as 'b'
short   // short integer
long    // long integer
double  // double-precision float

Using printf()

The printf() function is a powerful way to display output. To display a simple message:

printf("Welcome to Wofford!\n");

If you want to display one or more variables:

printf("%d + %d = %d", 123, var1, 123 + var1); // assume var1 is an integer

Some common formatters you can use with printf() are:

%d  // display as an integer
%f  // display as a float
%c  // display as a character
%e  // display in scientific notation
%s  // display a string (a string is a null-terminated character array in C)
%x  // hexadecimal notation
%%  // a literal % symbol

Some ways to display your output more precisely are:

%13d    // display as integer, but make it be at least 13 characters wide
%10f    // display as float, but make it be at least 10 characters wide
%.3f    // display as float, with 3 numbers following the decimal point
%10.3f  // display as float, with 3 numbers following the decimal point, and make it be at least 10 characters wide