Difference between revisions of "C Starting"

From Computer Science
Jump to: navigation, search
(Makefile)
(Makefile)
 
(One intermediate revision by the same user not shown)
Line 21: Line 21:
 
}
 
}
 
</pre>
 
</pre>
 +
gcc is documented at https://gcc.gnu.org/onlinedocs/
  
 
==Makefile==
 
==Makefile==
Line 33: Line 34:
  
 
%.o : %.c
 
%.o : %.c
gcc $(CFLAGS) $< -o $@
+
-gcc $(CFLAGS) $< -o $@
  
 
clean:
 
clean:

Latest revision as of 23:38, 5 September 2022

On CS Systems - gcc

For CS courses that use C, the gcc compiler is often used. This is already installed on the CS server. To get started do the following.

  • Use a terminal text editor (see Text Editors) to edit your C program file. Let's say your program is hello.c
  • Compile the program using the gcc command:
gcc hello.c -o hello.o

If you do not have any errors in your program, the file hello.o will be created.

  • Run the program by running:
./hello.o

You can use the classic "hello world" program as a first attempt.

#include <stdio.h>

int main(int argc, char *argv[]) {
  printf("Hello world!\n");
  return 0;
}

gcc is documented at https://gcc.gnu.org/onlinedocs/

Makefile

Rather than type the gcc command each time you want to compile, you can put the right commands into a Makefile and use the make command. The following is a basic Makefile which will compile all .c files in the current directory.

SHELL = /bin/sh
CFLAGS = -g -Wall -O0
SRCS = $(wildcard *.c)
OBJS = $(SRCS:.c=.o)

all: $(OBJS)

%.o : %.c
	-gcc $(CFLAGS) $< -o $@

clean:
	rm -f *.o

Save this file with the filename Makefile. Then type make to compile all of the .c files. Type make clean to remove the compiled .o files, to then recompile all .c files with the next make command.

Note that the make command invokes GNU Make, which is documented at https://www.gnu.org/software/make/manual/make.html