First, check to see if your computer already has XCode installed. Open up a terminal and type
gcc -v
If you see a message like
-bash: gcc: command not found
then you will need to install a compiler. Consult your distribution's documentation (or ask me) how to get gcc up and running. Otherwise, you will see some output like this (this output is from my Mac, yours will look different -- the important thing is that the command runs).
Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5664~105/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1 Thread model: posix gcc version 4.2.1 (Apple Inc. build 5664)
There are many text editors available for most distributions, but gedit is a nice simple one. Other than that, there are the two old standbys, vi (vim) and Emacs.
Create a folder for your programs in your home directory.
#include <stdio.h>
int main(int argc, char** argv) {
printf("Hello, world!\n");
return 0;
}
Now it's time to compile your program. Open up a terminal and type in (substituting whatever path you chose to put the source file in):
cd ~/ccode/example gcc -o hello hello.c ./hello
You should get the output
Hello, world!
If so, you have successfully compiled your first program!
"Make" is a handy utility that recompiles your programs for you by detecting when the source code is more recent than the executable. We will test it by trying to get it to recompile your hello file, changing the source code, and recompiling again. We'll learn more about how to use make in class soon.
In the same directory as hello.c, use your text editor to create a file called makefile (no .c or .txt extension), containing:
hello: hello.c gcc -O3 -Wall -o $@ $^
The space at the start of the second line above is a tab character, not 8 spaces (you can enter a tab by hitting the tab key). Note that make won't work unless you indent certain lines with tabs!
If you go to the MINGW prompt, and type
make
you should see a message like
make: `hello' is up to date.
Now change hello.c to print something else (maybe "Hello, world, again!") and save the file. Go back to the MINGW shell and type
make
once more. It will print the line
gcc -O3 -Wall -o hello hello.c
indicating that it has recompiled your program for you.