// hello.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
if (printf("hello, world\n") < 0)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
In order to run the program, it needs to be compiled. The process to compiling this simple C program is very easy on Linux.
Details
hello.c
- Generally, you name your C programs with the
.c
extension.
#include <stdio.h>
-
At the top of the file is a preprocessor directive,
#include
, which is replaced by contents of the file that is named afterwards. -
The
.h
part means this is a header file, but it is still a normal part of the “C” language. -
It’s necessary to import this “standard input output” library. It will provide the function required to print to the console.
#include <stdlib.h>
- This “standard library” provides the utilities, like variables, that are used within this program.
int main(void)
-
C programs all use a
main()
function as their entry point. Other functions can have different names, but this particular function is special, and is necessary to run the C program. -
Examples of this function might not include the
int
part before themain(void)
part, but here it is included as it is standard and expected when writing C code. Theint
means that this function returns a value of type “integer”, that is positive and negative whole numbers and zero. -
void
appears in the parenthesis to indicate that this function does not accept any arguments.
if (printf("hello, world\n") < 0)
-
This is what “calling” a function looks like. This function comes from the library that was imported. All this does is take the argument provided, a character string, and sends it to the “standard output”, which might be a console.
-
The function call is wrapped as a condition in an if block because if the function returns a negative integer, this indicates an error occurred.
return EXIT_FAILURE;
- If there’s an error, it’s useful to return from this program the integer value that commonly represents that a failure occurred, which the macro “EXIT_FAILRE” defines as 1.
return EXIT_SUCCESS;
- In the stdlib, EXIT_SUCCESS uses “#define” to replace any usage of it with the value 0. 0 is returned to the environment so that indicate the invocation of the program didn’t result in an error.
Sources:
- The C Programming Language 2nd Edition
- Effective C