You'll need a good text editor or IDE (Integrated Developer Environment) to write your C programs. TextEdit isn't a good choice because it doesn't use the plain text by default. TextWrangler is a free program from the App Store, or you can downloadSublime Text, which has an indefinite trial mode (this is our current favourite text editor).
How to learn C in Mac OS X: How to create a Hello World program in C
C differs from other programming languages, like Python, in that you need to compile programs before you can run them. You'll typically do this in C using the command "make". C programs end with the ".c" extension, and you'll run make to build a second file, that is the compiled program. The compiled file is what you run.
You can do all this from the command line, so let's see how to make a traditional "Hello, World!" program.
Open your text editor and save a file called "hello.c" in your Home folder.
Enter the following code:
Note that we use four single spaces (" ") to indent the "printf" and "return" lines. You can also use a single Tab space, and there are plenty of vibrant arguments as to which is better. My stance is always to use spaces unless I'm working on somebody else's code that uses tabs. What's most important is not to mix and match styles. Either press the Space bar four times or press the Tab key.
- With the "hello.c" file saved in your Home folder, it's time to compile it.
- Return to Terminal and enter cd ~ to make sure you're working in the Home directory.
- Enter make hello and press Return. Note that you don't include the ".c" extension.
- Terminal will display "cc hello.c -o hello". If it displays any errors, then go back and check your code.
- When it compiles, there will be a second file called just "hello" in the home folder.
- Enter ./hello to run the hello program. You will see "Hello, World!" at the command line.
This process is how you build and make programs in C, at least when you're starting. You write a C program in a text editor, and then compile it using make, and then run the compiled program to see the result.
Sign up for CIO Asia eNewsletters.