To get started with your very first program in C, you must first be sure a C compiler is installed on your machine. Our article on C Compilers and How to Set Them Up will help you get started.
Hello World! in C
Getting your first program off the ground is simple once you have the correct tools installed. First, open your preferred code editor and start and save a new file called hello.c.
The makeup of any file in C is going to be two things:
- Your preprocessing commands – indicated by a hash symbol plus the word include, you can list headers that are needed to operate your code here.
- Main function – int main () {<program goes here>} is your program. As indicated by the type it expects to return an integer. If successful, it will return 0 and execute. If an error is thrown, it will return an exit status code and show the error in the compiler.
Preprocessor
Let’s start with the preprocessor section:
#include <stdio.h>
The <stdio.h>
(standard input/output) header is in the standard library packaged with your compiler. This header defines variables, rules, and various functions for performing input and output. We need the <stdio.h>
header file to access the functions we need to print out “Hello, World” to our terminal.
The C preprocessor will take a look at the #include statement as well as any other definitions that begin with #
on the first pass through the code before compilation.
Main Function
All C files will have a main()
function that expects to return an integer indicating if the function succeeded or not in executing. Here’s our code to print out “Hello, World”:
int main(void) { printf("Hello, world!\n"); return 0; }
The void statement in between the parentheses simply means the function is not expecting any arguments.
The printf function comes from the <stdio.h>
header where it is defined. It is the function that will display the message on the terminal.
Conclusion
How you compile your file depends on which compiler you are using. Follow the instructions for your compiler when it comes to compiling C code. Once compiled, you can then run it. That’s all there is to it! Congrats – you have just written your first C program!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.