Basic compiling and running C programs on our system

  1. Create a file containing your C source code using the vim (or emacs) editor (% is the unix prompt in these examples):
    % vim add.c                 
    
    If you don't know how to use either editor, first run vimtutor to learn vim:
    % vimtutor
    

  2. gcc is the C compiler that will compile your C source code into an executable file you can run.
    To compile the add.c program:
    % gcc add.c           
    

    It is a good idea to compile with -g flag to include debugging information in the executable:
    % gcc -g add.c           
    

  3. If there were no compilation errors, then gcc creates an executable file named a.out that you can run:
    # list contents of directory to see that gcc created a.out file
    % ls			
    	a.out*   add.c
    
    # run a.out:
    % ./a.out	  
    
If you make changes to add.c and re-compile it, I'd suggest first removing the a.out from the previous compile (this way if the compilation fails you won't mistakenly run the old a.out and wonder why your changes are not showing up):
% rm a.out
% gcc -g add.c

Some other common gcc options:

-Wall to turn on all compiler warnings (this is usually a good idea):

% gcc -g -Wall add.c           

-o filename to specify the name of the executable to be something other than the default a.out:
% gcc -g -Wall -o add add.c           
# to run:
% ./add

-lm to link in the math library (it contains functions like sqrt, cos, sin, etc):
% gcc -g -Wall -o add add.c -lm          

make

Eventually, you will want to put the compilation commands in a makefile and then just run the command make to compile your program. Here is some more information on make and makefiles: make and makefiles